Repeats a group of statements for each element in a collection.
For Each element [ As datatype ] In group [ statements ] [ Exit For ] [ statements ] Next [ element ]
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.
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 CollectionFor EachMyObject As ObjectInMyCollection ' Iterate through elements. If CStr(MyObject.Text) = "Hello" Then ' If Text equals "Hello" Found = True ' Set Found to True.Exit For' Exit loop. End IfNext
Do...Loop Statements | Exit Statement | For...Next Statements | While...End While Statements