Repeats a group of statements a specified number of times.
For counter = start To end [ Step step ] [ statements ] [ Exit For ] [ statements ] Next [ counter ]
The step argument can be either positive or negative. The value of the step argument determines loop processing as follows:
Step value | Loop executes if |
---|---|
Positive or zero | counter <= end |
Negative | counter >= end |
The expressions start, end, and step are all evaluated only once, when the For statement is first encountered. They are not evaluated again, even if the loop statements change their constituent parts.
The counter variable is compared to end every time before the loop is entered. This includes the first time the For statement is executed. Therefore, if the value of start is past the value of end when the loop is entered, the loop is not executed, and execution passes immediately to the statement following the Next statement.
After the loop statements have executed, step is added to counter. At this point, the For statement again compares counter to end. As a result of this comparison, either the statements in the loop execute again, or the loop is terminated and execution continues with the statement following the Next statement.
Note Changing the value of counter while inside a loop can make it more difficult to read and debug your code.
The Exit For statement transfers control immediately to the statement following the Next statement. Any number of Exit For statements can be placed anywhere in the For...Next loop. Exit For is often used after evaluating some condition, for example with an If?Then...Else statement.
You can nest For...Next loops by placing one loop within another. Each loop must have a unique counter variable. The following construction is correct:
For I = 1 To 10
For J = 1 To 10
For K = 1 To 10
' Statements to operate with current values of I, J, and K.
Next K
Next J
Next I
Note If a Next statement is encountered before its corresponding For statement, or if a Next statement of an outer nesting level is encountered before the Next of an inner level, an error occurs.
This example uses the For...Next statement to create a string that contains 10 instances of the numbers 0 through 9, each string separated from the other by a single space. The outer loop uses a loop counter variable that is decremented each time through the loop.
Dim Words, Digit As Integer Dim MyString As StringFor
Words = 10To
1Step
-1 ' Set up 10 repetitions.For
Digit = 0To
9 ' Set up 10 repetitions. MyString = MyString & CStr(Digit) ' Append number to string.Next
Digit ' Increment counter. MyString = MyString & " " ' Append a space.Next
Words