excelvbaautofilterexcel-tableslistobject

deleting specific rows from a table


I would like to check through a table called "Sorted_Duplicate_Removal" for errors, blanks, and values of 0 and then remove these rows from the table. Unfortunately every time I run my code:

    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

I get an error about the "out of range" on either of the lines ending in ".delete". Any information would be appreciated


Solution

  • i just tested this one, seems to work... Tables are a bit tricky...

    the main idea is to use DataBodyRange.Rows(i - 1).Delete instead of .ListRows(i - 1).Delete

    example:

    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