Export (0) Print
Expand All

For Each...Next Statements

Repeats a group of statements for each element in a collection.

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

Parts

element
Required. Variable. Used to iterate through the elements of the collection. The data type of element must be such that the data type of the elements of group can be converted to it.
datatype
Required if element is not already declared. Data type of element. If element is declared outside this loop, you cannot use the As clause to redeclare 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

If element has not been declared outside this loop, you can declare it within the For Each statement. In this case, the scope of element is the body of the loop. However, you cannot declare element both outside and inside the loop.

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 MyCollection As New Collection
For Each MyObject As Object 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) | Collections in Visual Basic .NET | Do...Loop Statements | Exit Statement | For...Next Statements | Faster For...Next Loops | While...End While Statements | Do...Loop Statements (Conceptual) | For...Next Statements (Conceptual)

Show:
© 2014 Microsoft