Change length of For loop while in the loop

I did a simple test and found the same problem:

Sub Macro1()
    Dim x As Integer: x = 10

    For i = 1 To x
        If (i = 5) Then
            x = 15
        End If
    Next

    MsgBox (i)
End Sub

Looks like excel does precompile the limit of a for loop. You can change your loop to a while instead.

See this post

x = 2

While x <= lastRow
    cellDifference = Range("B" & (x)).Value - initialValue
    If Abs(cellDifference) > 1 Then
        'your code

        lastRow = lastRow + 1
    End If
    x = x + 1
Wend

Leave a Comment