Repeats a group of statements a specified number of times.
Syntax
For counter = start To end [Step step]
[statements]
[Exit For]
[statements]
Next [counter]
The For...Next statement syntax has these parts:
Part |
Description |
|---|---|
Counter |
A required numeric variable used as a loop counter. |
Start |
A required initial value for counter. |
End |
A required final value for counter. |
Step |
An optional step that is added to counter each time through the loop. If not specified, 1 is used. |
Statements |
Zero or more statements between For and Next that are executed each time through the loop. |
Step Argument
The step argument can be either positive or negative. The value of the step argument determines loop processing as follows:
Value of step argument |
Loop execute condition |
Positive or zero |
counter <= end |
Negative |
counter >= end |
After all statements in the loop have executed, step is added to counter. At this point, either the statements in the loop execute again (based on the same test that caused the loop to execute initially), or the loop is exited and execution continues with the statement following the Next statement.
A number of Exit For statements can be placed anywhere in the loop as an alternate way to exit. Exit For is often used after evaluating some condition, for example, If...Then, and transfers control to the statement immediately following Next.
You can nest For...Next loops by placing one For...Next loop within another. Give each loop a unique variable name as its counter. The following construction is correct:
For I = 1 To 10
For J = 1 o 10
For K = 1 To 10
...
Next K
Next J
Next I
If you omit counter in a Next statement, execution continues as if counter is included. If a Next statement is encountered before its corresponding For statement, an error occurs.