Reputation: 119
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
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.
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.
Upvotes: 2
Views: 1402
Reputation: 12353
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
Upvotes: 3
Reputation: 43585
The TableExists
function returns a boolean value, indicating whether the table exists. Based on this, a MsgBox
could be shown with some relevant info:
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
Upvotes: 0