Visual Basic Language Reference  

For Each...Next Statements

Repeats a group of statements for each element in an array or collection.

For Each element In group
   [ statements ]
[ Exit For ]
   [ statements ]
Next [ element ]

Parts

element
Required. Variable. Used to iterate through the elements of the collection or array. The data type of element must be such that the data type of the elements of group can be implicitly converted to it.
group
Required. Object variable. Must refer to an object collection or array.
statements
Optional. One or more statements between For Each and Next that are executed on each item in group.

Remarks

The For Each...Next loop is entered if there is at least one element in group. Once the loop has been entered, the statements are executed for the first element in group; if there are more elements in group, the statements in the loop continue to execute for each element. When there are no more elements, the loop is terminated and execution continues with the statement following the Next statement.

Any number of Exit For statements may be placed anywhere in the loop as an alternative way to exit. Exit For is often used after evaluating some condition, for example with an If?Then...Else statement, and transfers control to the statement immediately following Next.

You can nest For Each...Next loops by placing one loop within another. Each loop must have a unique element variable.

Example

This example uses the For Each...Next statement to search the Text property of all elements in a collection for the existence of the string "Hello". In the example, MyObject is a text-related object and is an element of the collection MyCollection. Both are generic names used for illustration purposes only.

Dim Found As Boolean = False
Dim MyObject, MyCollection As Object
For Each MyObject In MyCollection   ' Iterate through elements.
   If CStr(MyObject.Text) = "Hello" Then   ' If Text equals "Hello"
      Found = True   ' Set Found to True.
      Exit For   ' Exit loop.
   End If
Next

See Also

For Each...Next Statements (Conceptual) | Do...Loop Statements | Exit Statement | For...Next Statements | Faster For...Next Loops | While...End While Statements | Do...Loop Statements (Conceptual) | For...Next Statements (Conceptual)