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
Necessary in the line that starts with For – the name of a variable
Optional in the line that starts with End
type
Optional data type of the variable counter. Permitted types include: Int8, Int16, Int32, Int, Int64, Int128, UInt8, UInt16, UInt32, UInt, UInt64, and UInt128.
start
Necessary integer expression – the initial value of counter.
end
Necessary integer expression – the last value of counter.
step
Optional integer expression – the increment for the variable counter.
statements
Optional One or more statements between the lines that start with For and End. These statements execute while the variable (counter) is between the initial value (start) and the last value (end).
Or as an alternative, two or three groups of statements. The initial group starts with Begin, and executes the same as specified above. The subsequent groups start with When, and execute either when the Begin group cannot start, or after it completes. See the When statements section for more information.
End
Completes the statement. You can also use End For. The optional variable counter can only follow End For.

Instructions

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 more information.

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 information.

Examples

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

See also