检查名称表是否存在VBA Excel 2007
我试图确定是否存在一个表,使用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
但它仍然不起作用。
有没有人知道一个方法来得到这个工作?
任何帮助,将不胜感激。
error handling作为nheebuild议是正确的方法。
作为UDF,上面的build议会更快:
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
如果一个表存在,下面的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