Specifications

Section 9. Program Control Instructions
9-8
For ... Next
Repeats a group of instructions a specified number of times.
Syntax
For counter = start To end [ Step increment ]
[statementblock]
[Exit For]
[statementblock]
Next [counter [, counter][, ...]]
The For...Next statement has these parts:
Part Description
For Begins a For...Next loop control structure. Must appear
before any other part of the structure.
counter Numeric variable used as the loop counter. The variable
cannot be an array element or a record element.
start Initial value of counter.
To Separates start and end values.
end Final value of counter.
Step Indicates that increment is explicitly stated.
increment Amount counter is changed each time through the loop. If
you do not specify Step, increment defaults to one.
statementblock Program lines between For and Next that are executed the
specified number of times.
Exit For Only used within a For...Next control structure to provide
an alternate way to exit. Any number of Exit For
statements may be placed anywhere in the For...Next loop.
Often used with the evaluation of some condition (for
example, If...Then), Exit For transfers control to the
statement immediately following the Next.
Next Ends a For...Next loop. Causes increment to be added to
counter.
The Step value controls loop execution as follows:
When Step is Loop executes if
Positive or 0 counter <= end
Negative counter >= end
Once the loop has been entered and all the 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 in
the first place), or the loop is exited and execution continues with the statement
following the Next statement.
Tip Changing the value of counter while inside a loop can make the
program more difficult to read and debug.
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: