从 table 中删除特定行

deleting specific rows from a table

我想检查名为“Sorted_Duplicate_Removal”的 table 中的错误、空白和 0 值,然后从 table 中删除这些行。不幸的是,每次我 运行 我的代码:

    Dim i As Integer
For i = 2 To Worksheets("Resource Group Table").ListObjects("Sorted_Duplicate_Removal").DataBodyRange.Rows.Count + 1
    If Worksheets("Resource Group Table").Range("X" & i).Text = "#N/A" Then
        Worksheets("Resource Group Table").ListObjects("Sorted_Duplicates_Removal").ListRows(i - 1).Delete
    Else
        If Worksheets("Resource Group Table").Range("X" & i).Value = "0" Then
        Worksheets("Resource Group Table").ListObjects("Sorted_Duplicates_Removal").ListRows(i - 1).Delete
        End If
    End If
Next i

我在以“.delete”结尾的任何一行上收到有关“超出范围”的错误。 任何信息将不胜感激

我刚刚测试了这个,似乎工作...表格有点棘手...

主要思想是使用DataBodyRange.Rows(i - 1).Delete而不是.ListRows(i - 1).Delete

示例:

Sub test()

Dim i As Integer
For i = Worksheets("Resource Group Table").ListObjects("Sorted_Duplicate_Removal").DataBodyRange.Rows.Count + 1 To 2 Step -1
    With ActiveSheet.ListObjects("Sorted_Duplicate_Removal")
    If Worksheets("Resource Group Table").Range("X" & i).Text = "#N/A" Then
        .DataBodyRange.Rows(i - 1).Delete
    Else
        If Worksheets("Resource Group Table").Range("X" & i).Value = "0" Then
        .DataBodyRange.Rows(i - 1).Delete
        End If
    End If
    End With
Next i

End Sub

删除 Excel Table

中的过滤行
  • 适当调整列:仅当table从第A列开始时,字段24表示第X列。您也可以使用 header 而不是 24,例如.ListColumns("Whatever").Index.
Option Explicit

Sub DeleteFilteredRows()
    
    Dim Criteria As Variant: Criteria = Array("", "0", "#N/A")
    
    Dim tbl As ListObject
    Set tbl = ThisWorkbook.Worksheets("Resource Group Table") _
        .ListObjects("Sorted_Duplicate_Removal")
    
    Dim dvrg As Range ' Data Visible Range
    
    With tbl
        If .ShowAutoFilter Then
            If .AutoFilter.FilterMode Then .AutoFilter.ShowAllData
        End If
        .Range.AutoFilter 24, Criteria, xlFilterValues
        On Error Resume Next
            Set dvrg = .DataBodyRange.SpecialCells(xlCellTypeVisible)
        On Error GoTo 0
        .AutoFilter.ShowAllData
    End With
    
    If Not dvrg Is Nothing Then dvrg.Delete xlShiftUp
    
End Sub