我在excel表中有几个表。每个都有唯一的表名。我想知道一张桌子上是否有一个名字" Table123"当前表格中是否存在。
有人可以帮我这个吗?
由于 Jeevan
答案 0 :(得分:5)
TableExists = False
On Error GoTo Skip
If ActiveSheet.ListObjects("Table123").Name = "Table123" Then TableExists = True
Skip:
On Error GoTo 0
此代码将起作用并避免循环和错误
答案 1 :(得分:3)
您可以列出形状集合并比较这样的名称
Sub callTableExists()
MsgBox tableExists("Table1", "Shapes")
End Sub
Function TableExists(tableName As String, sheetName As String) As Boolean
Dim targetSheet As Worksheet
Set targetSheet = Worksheets(sheetName)
Dim tbl As ListObject
With targetSheet
For Each tbl In .ListObjects
If tbl.Name = tableName Then TableExists = True
Next tbl
End With
End Function
答案 2 :(得分:3)
这是一个替代功能:
Function TableExistsOnSheet(ws As Worksheet, sTableName As String) As Boolean
TableExistsOnSheet = ws.Evaluate("ISREF(" & sTableName & ")")
End Function
答案 3 :(得分:0)
另一种方法,使用有点懒的方法来捕获错误:
sysctl
答案 4 :(得分:0)
尝试此操作,使用err获取数据表状态信息 另外,请考虑在不活动的工作表上测试数据表。
Sub Test_TableNameExists()
TableNm = "Table00"
MsgOutput = TableNm & vbTab & TableNameExists(TableNm)
End Sub
Private Function TableNameExists(nname) As Boolean '#Table #Exist
'Returns TRUE if the data table name exists
'Can test table on inactive sheet
Dim x As Object
On Error Resume Next
'use Range(nname).Parent to get data table sheet name.
'So the function can test data table on inactive sheet.
Set x = Range(nname).Parent.ListObjects(nname)
If Err = 0 Then TableNameExists = True _
Else TableNameExists = False
End Function
答案 5 :(得分:0)
不使用 GoTo
,这比适当的要强大得多。
Set TableExists = False
On Error Resume Next
If ActiveSheet.ListObjects("Table123").Name = "Table123" Then Set TableExists = True
请注意,这适用于单行,因此需要行继续符 _
以保持较大语句的可读性。