Search code examples
excelvbaloopsdelete-row

Deleting Rows Based on Text Values in Specific Column


enter image description here I have written a short macro to delete all rows that have a value of "Not Applicable" in column I, for the "Budget" tab of my workbook.

The macro does not seem to be doing anything when I run it through my testing:

Sub Remove_NA_Macro_Round_2()
    With Sheets("Budget") 'Applying this macro to the "Budget" sheet/tab.

        'Establishing our macro range parameters
        Dim LastRow As Long
        Dim i As Long

        'Setting the last row as the ending range for this macro
        LastRow = .Range("I50").End(xlUp).Row

        'Looping throughout all rows until the "LastRow" ending range set above
        For i = LastRow To 1 Step -1
            If .Range("I" & i).Value = "Not Applicable" Then
                .Range("I" & i).EntireRow.Delete
            End If
        Next
    End With
End Sub

I appreciate any help!


Solution

  • Alternatively, when deleting rows based on a condition, it is faster to use a filter then looping.

    Dim rng As Range
    Set rng = ThisWorkbook.Sheets("Sheet1").Range("A1:I" & Cells(Rows.Count, "I").End(xlUp).Row)
    
    Application.DisplayAlerts = False
        With rng
            .AutoFilter
            .AutoFilter field:=9, Criteria1:="Not Applicable"
            rng.Resize(rng.Rows.Count - 1).Offset(1).SpecialCells(xlCellTypeVisible).Delete 'deletes the visible rows below the first row
            .AutoFilter
        End With
    Application.DisplayAlerts = True