循环遍历表并删除数据

问题描述 投票:1回答:2

我有以下代码生成错误。

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

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

对象变量或未设置块变量

我有以下代码工作但由于某种原因删除我想要离开的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
excel vba loops excel-2013
2个回答
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


0
投票

尝试使用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”。

© www.soinside.com 2019 - 2024. All rights reserved.