For...To Statement

Executes a sequence of statements for all values in a range.

Syntax

For counter [ As type ] = start To end [ Step step ]
    [ statements ]
End For [ counter ]

Parts

counter
Required in the For line — An integer variable
Optional in the End For line
type
Optional — The data type of counter.
start
Required — An integer expression and the initial value of counter.
end
Required — An integer expression and the last value of counter.
step
Optional — An integer expression and the increment for counter.
statements
Optional — One or more statements between the For and End For lines. These execute as long as counter is between start and end.
Alternatively, two or three groups of statements. The first group starts with Begin, and executes the same as specified above. The subsequent groups start with When, and execute either when the Begin group can not start, or after it completes. See the When statements section for more details.
End For
Completes the For statement.

Details

Notice: the End For line is not the same as the Exit For statement.

Use the For...To structure when you must execute one or more statements again and again. It is recommended when you can be sure how many times the statements must execute. Control depends on the counter variable specified in the For line. Other structures are possibly more flexible. See the See also section below for details.

Usual execution

Exit For

The Exit For statement can stop a For...To statement. Exit For immediately moves control to the statement after End For.

When statements

To find if a For...To statement completed because the counter became out-of-range, use the When %Done statement.

To find if a For...To statement was not executed because the counter was initially out-of-range, use the When %None statement.

See Begin...When Statements for more details.

Examples

For index As Int = 1 To 5
    #Debug.Print index
End For
#Debug.PrintLine

See also