Search code examples
excelvba

Removing rows with one of three conditions


I'm trying to remove rows with the condition that the string in the cells in column A contains "--" or "-4" or "" (empty). I'd do it with a normal filter, but that gives me max two conditions.

Sub Delete_Rows()
Dim cell As Range
For Each cell In Range("A:A")
    If cell.Value = "*--*" Or cell.Value = "*-4*" Then
        cell.EntireRow.Delete
    End If
Next cell
End Sub

Solution

  • Please, test the next version. It uses an array for iteration and a Union range to delete rows at once, at the end of the code:

    Sub Delete_Rows3Cond()
    Dim sh As Worksheet, lastR As Long, rngDel As Range, arr, i As Long
    
    Set sh = ActiveSheet
    lastR = sh.Range("A" & sh.rows.count).End(xlUp).row
    
    arr = sh.Range("A1:A" & lastR).Value2 'place the range in an array for faster iteration/processing only in memory
    For i = 1 To UBound(arr)
        If arr(i, 1) = "" Or arr(i, 1) Like "*--*" Or arr(i, 1) Like "*-4*" Then
            addToRange rngDel, sh.Range("A" & i) 'create the union range
        End If
    Next
    If Not rngDel Is Nothing Then rngDel.EntireRow.Delete xlUp
    End Sub
    
    Private Sub addToRange(rngU As Range, Rng As Range) 'I creates the Union range
        If rngU Is Nothing Then
            Set rngU = Rng
        Else
            Set rngU = Union(rngU, Rng)
        End If
    End Sub
    

    Deleting a row at a time, takes a lot of time and you need to process only the range containing data...

    Please, send some feedback after testing it.