我有以下代码会产生错误。
我想遍历活动工作表上的所有表,并删除除代码中指定的两个数据以外的数据。
Sub Clear_Tables()
Dim tbl As ListObject
For Each tbl In ActiveSheet.ListObjects
If tbl <> "Table_Extracted_Data_Summary" Or tbl <> "Manual_Entries" Then
tbl.DataBodyRange.Rows.Delete
Else
End If
Next tbl
End Sub
错误代码是:
运行时错误“ 91”:
对象变量或未设置带块变量
我有以下代码可以正常工作,但是由于某种原因,如果删除了我要离开的两个表的内容,
Sub Clear_Tables()
'PURPOSE: Loop through and apply a change to all Tables in the Active Excel
Sheet
Dim TableToCheck As ListObject
For Each TableToCheck In ActiveSheet.ListObjects
If TableToCheck.Name = "Table_Extracted_Data_Summary" Or
TableToCheck.Name = "Manual_Entries" Then 'Name of Table you do NOT want to
update
If Not (TableToCheck.DataBodyRange Is Nothing) Then
TableToCheck.DataBodyRange.ClearContents
End If
Next TableToCheck
End Sub
答案 0 :(得分:1)
将第二个代码修改为以下代码。您需要名称不为A且不是B的表。
Sub Clear_Tables()
'PURPOSE: Loop through and apply a change to all Tables in the Active Excel
Sheet
Dim TableToCheck As ListObject
For Each TableToCheck In ActiveSheet.ListObjects
If TableToCheck.Name <> "Table_Extracted_Data_Summary" And _
TableToCheck.Name <> "Manual_Entries" Then 'Name of Table you do NOT want to update
If Not (TableToCheck.DataBodyRange Is Nothing) Then
TableToCheck.DataBodyRange.ClearContents
End If
End If
Next TableToCheck
End Sub
或在适当的情况下从ClearContents
还原为Rows.Delete
。
答案 1 :(得分:0)
尝试使用AND运算符(或可能需要括号):
Sub Clear_Tables()
Dim tbl As ListObject
For Each tbl In ActiveSheet.ListObjects
If tbl <> "Table_Extracted_Data_Summary" And tbl <> "Manual_Entries" Then
tbl.DataBodyRange.Rows.Delete
End If
Next tbl
End Sub
否则,您的语法似乎很好。
我无法重现您的错误“ 91”。