0

Lets say I have a For loop similar to this:

Sub forLoop()
Dim firstRow As Integer
Dim lastRow As Integer
Dim aRow As Integer
firstRow=5
lastRow=200
For aRow = firstRow to lastRow
   If (something) Then  //lets say it happened when aRow = 18
       aRow=aRow+1  //=> aRow=19 
       ...
   End If
Next aRow  //which one ? will next aRow be 19 or 20?

And I increment a aRow variable inside the loop. Would it result in that variable being incremented twice as much?

3 Answers 3

2

If you'll debug your code you can see the value yourself. Below code results in

Sub Demo()
    Dim firstRow As Integer
    Dim lastRow As Integer
    Dim aRow As Integer
    firstRow = 5
    lastRow = 200
    For aRow = firstRow To lastRow
        If aRow = 7 Then
            aRow = aRow + 1
        End If
        Debug.Print aRow
    Next aRow
End Sub

output as

enter image description here

Here, aRow = aRow + 1 increments the value of aRow by 1 and is subsequently reflected in loop.

Sign up to request clarification or add additional context in comments.

Comments

1

Yes, it does.

Run the this simple script:

Sub forLoop()
Dim i As Long
For i = 1 To 100
    If i Mod 5 = 0 Then
        i = i + 1
    End If

Debug.Print i
Next i
End Sub

As you can see with the output, when i is 5 it is forced to 6 and then the next loop is 7.

enter image description here

Comments

1

You will get a one-time bump:

Sub forLoop()
    Dim firstRow As Integer
    Dim lastRow As Integer
    Dim aRow As Integer
    Dim i As Long

    firstRow = 5
    lastRow = 200
    i = 1

    For aRow = firstRow To lastRow
       If (aRow = 18) Then
           aRow = aRow + 1
       End If
       Cells(i, "A") = aRow
       i = i + 1
    Next aRow
End Sub

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.