For Each...Next Statement 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, MyObject, MyCollection
Found = False    ' Initialize variable.
For Each MyObject In MyCollection    ' Iterate through each element. 
    If MyObject.Text = "Hello" Then    ' If Text equals "Hello".
        Found = True    ' Set Found to True.
        Exit For    ' Exit loop.
    End If
Next