For Each Statement

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


For Each variable [ As type ] In object_expression
    [ statements ]
End [ For ]


Necessary name of A variable
Optional data type
Necessary object expression, string expression, or array literal.
Optional One or more statements between the line that starts with For Each and the line that starts with End. These execute one time for each item in a collection.
As an alternative, 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 cannot start, or after it completes. See the When statements section 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.


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

Usual execution


Exit For

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

When statements

To find if a For Each statement completed because it went through all of the items, use the When %Done statement.

To find if a For Each statement was not executed because the object_expression was empty, use the When %None statement.

See Begin...When Statements 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

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

See also