Using For Each...Next
A For Each...Next loop is like a For...Next loop. Instead of repeating the statements a specified number of times, a For Each...Next loop repeats a group of statements for each item in a collection of objects or for each element of an array. This is especially helpful if you don't know how many elements are in a collection.
The following examples illustrates the use of the for each next loop:
Example 1:
Sub DisplayDictionaryItems()
Dim d, item, item1
Set d = CreateObject("Scripting.Dictionary")
d.Add "0", "Athens"
d.Add "1", "Belgrade"
d.Add "2", "Cairo"
For Each item In d.Items
'Will print Items here
Next
End Sub
Example 2:
Sub DisplayArrayItems()
Dim myArray, item
myArray = Array("Apple", "Banana", "Cherry")
For Each item In myArray
'Each element of the array.
Next
End Sub
Example 3:
Sub DisplayCollectionItems()
Dim coll, item
Set coll = CreateObject("Scripting.Dictionary")
coll.Add "A", "Apple"
coll.Add "B", "Banana"
coll.Add "C", "Cherry"
' Corrected iteration to log values
For Each item In coll.Items
'The items will be printed here
Next
End Sub