遍历表并删除数据

Loop through tables and delete data

我有以下生成错误的代码。

我想遍历活动工作表上的所有表并删除代码中指定的两个表之外的数据。

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':

未设置对象变量或 With 块变量

我有以下代码可以工作,但出于某种原因,如果删除了我想离开的 2 个表的内容

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

尝试使用 AND 运算符(OR 可能需要括号):

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”。

将您的第二个代码修改为以下内容。您想要名称不是 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