For Each Statement

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

Syntax

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

Parts

variable
Mandatory name of a variable.
type
Optional data type of variable.
object_expression
Mandatory object reference, string expression, or array literal.
statements
Optional One or more statements between the lines that start with For Each and End. These execute one time for each item in a collection.
The alternative is two or more groups of statements. The first group starts with Begin, and executes the same as specified above. The subsequent groups start with When, and execute (1) when the group Begin cannot start, or (2) after it completes. See the When statements section for more information.
End
Completes the statement. You can also use End For.
You can change the syntax of this part. See @Option Directive for more information.

Instructions

End For is not the same as Exit For.

Usual execution

TODO

Exit For

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

When statements

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

To find if a loop of type For Each was not executed because object_expression is empty, use When %None.

See Begin…When Statements for more information.

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