For Each...In Statement

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

Syntax

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

Parts

variable
Required — A variable
type
Optional — A data type
objectExpression
Required — An object or string expression, or an array literal.
statements
Optional — One or more statements between For Each and End For. These execute one time for each item in a collection.
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 Each structure.

Details

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...In statement. Exit For immediately moves control to the statement after End For.

When statements

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

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

See Begin...When Statements for more details.

Examples

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