从表中删除特定行

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

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

    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”结尾的任何一行上收到有关“超出范围”的错误。 任何信息将不胜感激

excel vba autofilter excel-tables listobject
2个回答
2
投票

删除 Excel 表格中筛选的行

  • 适当调整列:仅当表格从列
    A
    开始时,字段
    24
    才表示列
    X
    。您还可以使用标题代替
    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

1
投票

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

主要思想是使用

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
© www.soinside.com 2019 - 2024. All rights reserved.