我正在尝试使用VBA Excel 2007确定表是否存在,如果存在则删除它。
我循环遍历一组表名。
我的代码如下:
' 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
但它仍然不起作用。
有人知道让这个工作的方法吗?
任何帮助都将不胜感激。
答案 0 :(得分:5)
nhee建议的错误处理是正确的方法。
作为一个UDF,上面的建议会更快:
SELECT cust.Name, rec.ProductID,
CASE WHEN rec.IsPaid IS NULL THEN 0 ELSE 1 END
FROM Customer AS [cust]
LEFT JOIN Records AS [rec]
ON cust.CustID = rec.CustID
答案 1 :(得分:2)
如果表存在,以下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