Repeats a group of statements for each element in an array or collection.
For Each element In group [ statements ] [ Exit For ] [ statements ] Next [ element ]
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 MyObject, MyCollection As ObjectFor Each
MyObjectIn
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 IfNext