【问题标题】:VBA Excel error handling when checking if a particular table exists using table name使用表名检查特定表是否存在时的 VBA Excel 错误处理
【发布时间】:2018-07-17 16:18:39
【问题描述】:

当使用表格名称检查表格的表格时,有一个线程几乎可以提供我所需要的内容。这是这里... 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

如果表不存在,它会直接进入错误处理程序,这很好,但是我在函数中有其他代码,当错误最终会使用相同的错误处理程序时。因此,我无法显示特定的 msgbox,说明该表不存在。

如果表不存在,有没有办法显示一个 msgbox,它不使用与函数其他部分相同的错误处理程序。

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    您可以创建一个单独的函数来检查表是否存在,并且与主程序错误处理程序无关。

    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
    

    【讨论】:

    • 谢谢。这对我有帮助
    【解决方案2】:

    TableExists函数返回一个布尔值,表示表是否存在。基于此,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
    

    【讨论】:

      猜你喜欢
      • 2013-01-31
      • 2013-03-06
      • 1970-01-01
      • 1970-01-01
      • 2018-12-05
      • 1970-01-01
      • 1970-01-01
      • 2022-07-10
      • 1970-01-01
      相关资源
      最近更新 更多