Un loop For Each...Next è simile a un loop For...Next. Anziché ripetere le istruzioni un numero specificato di volte, un loop For Each...Next ripete un gruppo di istruzioni per ogni elemento di una raccolta di oggetti o per ogni elemento di un array. Ciò risulta particolarmente utile se non si sa quanti elementi sono contenuti in una raccolta.
Negli esempi seguenti viene illustrato l'uso del loop successivo For Each.
Esempio 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
Esempio 2
Sub DisplayArrayItems()
Dim myArray, item
myArray = Array("Apple", "Banana", "Cherry")
For Each item In myArray
'Each element of the array.
Next
End Sub
Esempio 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