excelvbainfinite-loopnot-operator

Infinite For...Next loop: how do I fix it?


I'm trying to delete all rows with cell values non equivalent to one of the values from array Ar(). When I put logical operator NOT loop goes infinite for some reason (excel freezes). In opposite it works flawlessly, in case if I would want to delete rows containing values from array.

The problem is on line:

If Not .Cells(i, 10).Value = Ar(j) Then

My code:

Sub Tims()
    Dim LastRow As Long, LR As Long
    Dim i As Long, j As Long
    Dim t As Integer
    Dim Ar() As String

    Worksheets("Start").Activate
    t = Count("a", Range("A3:A14"))
    LR = Range("I3:I10").End(xlDown).Row
    Worksheets("Master").Activate
    Sheets("Master").Range("A100:A" & 100 + LR - 3).Value = Sheets("start").Range("I3:I" & LR).Value

    With Worksheets("Master")
        For j = 1 To LR - 2
            ReDim Preserve Ar(j)
            Ar(j) = Cells(99 + j, 1)
        Next j
    End With

    With Worksheets("Master")
        LastRow = .Cells(.Rows.Count, "B").End(xlUp).Row
    End With

    Worksheets("Master").Activate

    For j = 1 To LR - 2
        For i = 1 To LastRow
            With Worksheets("Master")
                If Not .Cells(i, 10).Value = Ar(j) Then
                    .Cells(i, 10).EntireRow.Delete
                    i = i - 1
                End If
            End With
        Next i
    Next j

End Sub

Solution

  • The line causing the infinite loop is this one:

    i = i - 1
    

    Get rid of it, and replace this

    For i = 1 To LastRow
    

    with this

    For i = LastRow To 1 Step -1
    

    I see why you tried i = i - 1 in order to avoid skipping a row each time a row is deleted. But that doesn't work: if a row gets deleted, then it is replaced by an empty row at the bottom of your table, and eventually you reach it. This empty row obviously does not contain any of the values in your array Ar(j), so it gets deleted and replaced by another empty row, which then gets deleted and replaced by another empty row, ad infinitum.

    You could have figured this out yourself had you stepped through your code in debug mode.

    Instead, just iterate from the bottom up using Step -1.