检查命名表是否存在VBA Excel 2007
我试图使用VBA Excel 2007确定表是否存在,如果存在,则将其删除 我正在遍历一个表名数组 我的代码如下:检查命名表是否存在VBA Excel 2007,vba,excel,Vba,Excel,我试图使用VBA Excel 2007确定表是否存在,如果存在,则将其删除 我正在遍历一个表名数组 我的代码如下: ' Allocate Dim lIndex As Long ' Allocate table header values in array Dim sTableNames(1 To Constants.lNumTables) As String ' Populate array sTableNa
' Allocate
Dim lIndex As Long
' Allocate table header values in array
Dim sTableNames(1 To Constants.lNumTables) As String
' Populate array
sTableNames(1) = Constants.sTableNameKpiAllIncidents
sTableNames(2) = Constants.sTableNameSlaAllManualHelpdeskIncidents
sTableNames(3) = Constants.sTableNameSlaAllManualIncidents
sTableNames(4) = Constants.sTableNameKpiAllAutomaticIncidents
' Work in worksheet Statistics
With Worksheets(Constants.sSheetNameStatistics)
' Loop through all tables
For lIndex = 1 To UBound(sTableNames)
' Check if table already exists
If Not .ListObjects(sTableNames(lIndex)) Is Nothing Then
' Delete table
.ListObjects(sTableNames(lIndex)).Delete
End If
Next
End With
只要工作表中存在这些表,我的代码就可以工作。我也试过更换线路
If Not .ListObjects(sTableNames(lIndex)) Is Nothing Then
排队
If .ListObjects(sTableNames(lIndex)).Count > 0 Then
但它仍然不起作用
有人知道如何让它发挥作用吗
如果有任何帮助,我们将不胜感激。如果表存在,以下UDF将返回布尔值
Function TableExists(ws As Worksheet, tblNam As String) As Boolean
Dim oTbl As ListObject
For Each oTbl In ws.ListObjects
If oTbl.Name = tblNam Then
TableExists = True
Exit Function
End If
Next oTbl
TableExists = False
End Function
nhee建议的错误处理是正确的方法 作为一个UDF,上述建议将更快:
Function TableExists(ws As Worksheet, tblNam As String) As Boolean
Dim oTbl As ListObject
On Error Resume Next
Set oTbl = ws.ListObjects(tblNam)
TableExists = Not oTbl Is Nothing
End Function
你有什么错误?“脏”的快速修复方法是在
…Delete
行之前添加On Error Resume Next
。我得到运行时错误“9”:下标超出范围它使Excel在遇到错误时不会中断代码执行。这是“脏”的,因为所有错误的出现都是有原因的(在您的情况下:宏试图删除不存在的内容),跳过它可能会忽略其他错误。谢谢!如果没有的话,我以前也插入过这行。ListObjects(sTableNames(lIndex))那时什么都不是,它工作了!