[英]VBA Excel error handling when checking if a particular table exists using table name
There is a thread which almost gives me exactly what i need when checking a sheet for a table using the table name.在使用表格名称检查表格的工作表时,有一个线程几乎给了我我需要的东西。 This is here... VBA Excel check if a particular table exist using table name
这是在这里... VBA Excel 使用表名检查特定表是否存在
TableExists = False
On Error GoTo Skip
If ActiveSheet.ListObjects("Table123").Name = "Table123" Then TableExists = True
Skip:
On Error GoTo 0
If the table does not exist it goes straight to the error handler, this is fine however i have other code in the function that when errors would end up using the same error handler.如果表不存在,它会直接进入错误处理程序,这很好,但是我在函数中有其他代码,当错误最终会使用相同的错误处理程序时。 Because of this i cannot display a specific msgbox stating that the table does not exist.
因此,我无法显示说明该表不存在的特定 msgbox。
Is there a way to display a msgbox if the table does not exist, one that doesn't use the same error handler as other parts of the function.如果表不存在,是否有一种方法可以显示 msgbox,该表不使用与函数的其他部分相同的错误处理程序。
You can create a separate function which can check table exists and has nothing to do with a main routine error handler.您可以创建一个单独的函数,该函数可以检查表是否存在并且与主例程错误处理程序无关。
Function tableExist(Sht As Worksheet, tblName As String) As Boolean
On Error Resume Next
tableExist = Sht.ListObjects(tblName).Name = tblName
On Error GoTo 0
End Function
Sub test()
If tableExist(ActiveSheet, "Table1234") Then
' write your code here
End If
End Sub
The TableExists
function returns a boolean value, indicating whether the table exists. TableExists
函数返回一个布尔值,指示表是否存在。 Based on this, a MsgBox
could be shown with some relevant info:基于此,可以显示带有一些相关信息的
MsgBox
:
Public Sub TestMe()
If TableExists("Table1243", ActiveSheet) Then
MsgBox "Table Exists"
Else
MsgBox "Nope!"
End If
End Sub
Public Function TableExists(tableName As String, ws As Worksheet) As Boolean
On Error GoTo TableExists_Error
If ws.ListObjects(tableName).Name = vbNullString Then
End If
TableExists = True
On Error GoTo 0
Exit Function
TableExists_Error:
TableExists = False
End Function
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.