Wojtek Wencel
Wojtek Wencel

Reputation: 2117

Removing rows while looping through them

I'm trying to remove all rows form a Range that have a cell with value "Totals" in them. I tried something like this:

For Each cell In rng
    If CStr(cell.Value) = "Totals" Then
        cell.EntireRow.Delete
    End If
Next cell

The problem is that whenever there are two rows both containing a cell with "Totals" only the first row gets removed. How can I solve that?

Upvotes: 0

Views: 91

Answers (1)

Alex P
Alex P

Reputation: 12489

You'll need a pattern like this:

Dim numberOfRows as Integer, rw as Integer, col as Integer

numberOfRows = 100  // You probably want to set this using your `rng` object 
col = 1 // column 'A' (but set for your situation)

For rw = numberOfRows to 1 Step -1
    If CStr(Cells(rw, col)) = "Totals" Then
        Cells(rw, col).EntireRow.Delete
    End If
Next rw

EDIT Two alternative methods

Suppose I have data in A1:C3 as follows:

     A    B        C
1    1    2        3
2    4    Totals   5
3    6    7        8

I want to delete any rows containing Totals. Here are two ways to do it:

Sub MarkToDelete()
    Dim rng As Range, cl As Range, rw As Integer

    Set rng = Range("A1:C3")

    For Each cl In rng
        If cl = "Totals" Then
            Cells(cl.Row, 4) = "DELETE" //i.e. in column D add a note to delete
        End If
    Next cl

    For rw = rng.Rows.Count To 1 Step -1
        If Cells(rw, 4) = "DELETE" Then
            Cells(rw, 4).EntireRow.Delete
        End If
    Next rw
End Sub

Sub LoopRemove()
    Dim rw As Integer, col As Integer

    Set rng = Range("A1:C3")

    For rw = rng.Rows.Count To 1 Step -1
        For col = 1 To rng.Columns.Count
            If Cells(rw, col) = "Totals" Then
                Cells(rw, col).EntireRow.Delete
            End If
        Next col
    Next rw
End Sub

Upvotes: 3

Related Questions