For Each...In 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
Necessary name of A variable
type
Optional data type
object_expression
Necessary object expression, string expression, or array literal.
statements
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.
End
Completes the statement. You can also use End For.

Instructions

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 object_expression was empty, use the When %None statement.

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