For Each...In Statement

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


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


Required — A variable
Optional — A data type
Required — An object or string expression, or an array literal.
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.
Completes the For Each statement. Alternatively, you can use End For.


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.


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