For Each Statement

Runs a sequence of statements for each item in a data structure.


For Each element [ As type ] In group
    [ statements ]
End [ For ]


Mandatory variable name declaration.
Usually optional data type of element.
Mandatory if group is an array literal between braces ({ }) and element is without a type character.
Mandatory collection object, string expression, or array literal.
Optional One or more statements between the lines that start with For Each and End. These run one time for each item in a collection.
The alternative is two or more groups of statements. The initial group starts with Begin, and runs the same as specified above. The subsequent groups start with When, and run when the group after Begin cannot start, or after it completes. See the section When statements for more information.
Completes the statement. You can also use End For.
You can change the syntax of this part. See @Option Directive for more information.


End For is not the same as Exit For.

Use the construct For Each when you must run one or more statements again and again. It is recommended when you must run statements for each item in a collection. Other loop constructs are possibly more flexible. See the See also section below for more information.

Usual operation


Loop-index counter

With loops of this type, you can use a magic integer constant %INDEX. It starts at zero (0) and increases by one (1) with each iteration.

If you nest loops of this type, %INDEX can refer to a different loop to what you think. Thus, we recommend that you make special counter variables as an alternative, if necessary.

Exit For

The statement Exit For can stop this type of loop. Exit For immediately runs the statement after End.

Exit can also stop more than one nested loop. You can use the statement «Exit For, For» in the inner loop to stop two loops.

When statements

To find if a loop of this type completed because it went through all of the items, use When DONE. To find if a loop of this type did not run because group is null or empty, use When NONE. See Exit When Clause for more information.


Elements in an array literal

For Each day As String In { "Mon", "Tue", "Wed", "Thu", "Fri" }
    ' do something
End For

Characters in a string

Var s = "ViviFire"
For Each c As Char In s
    ' do something
End For

See also