VBA Flow control structures
For loop
The For loop is used to repeat the enclosed section of code a given number of times. The following simple example illustrates the basic syntax:
Dim i as Integer 'Declaration of i
For i = 1 to 10 'Declare how many times the loop shall be executed
Debug.Print i 'The piece of code which is repeated
Next i 'The end of the loop
The code above declares an Integer i. The For loop assigns every value between 1 and 10 to i and then executes Debug.Print i - i.e. the code prints the numbers 1 through 10 to the immediate window. Note that the loop variable is incremented by the Next statement, that is after the enclosed code executes as opposed to before it executes.
By default, the counter will be incremented by 1 each time the loop executes. However, a Step can be specified to change the amount of the increment as either a literal or the return value of a function. If the starting value, ending value, or Step value is a floating point number, it will be rounded to the nearest integer value. Step can be either a positive or negative value.
Dim i As Integer
For i = 1 To 10 Step 2
Debug.Print i 'Prints 1, 3, 5, 7, and 9
Next
In general a For loop would be used in situations where it is known before the loop starts how many times to execute the enclosed code (otherwise a Do or While loop may be more appropriate). This is because the exit condition is fixed after the first entry into loop, as this code demonstrates:
Private Iterations As Long 'Module scope
Public Sub Example()
Dim i As Long
Iterations = 10
For i = 1 To Iterations
Debug.Print Iterations 'Prints 10 through 1, descending.
Iterations = Iterations - 1
Next
End Sub
A For loop can be exited early with the Exit For statement:
Dim i As Integer
For i = 1 To 10
If i > 5 Then
Exit For
End If
Debug.Print i 'Prints 1, 2, 3, 4, 5 before loop exits early.
Next