For Each...Nextループは、For...Nextループに似ています。For Each...Nextループは、文を指定の回数繰り返すのではなく、オブジェクトのコレクション内の各アイテムまたは配列の各要素について文のグループを繰り返します。これは、コレクション内の要素の数が不明な場合に特に役立ちます。
次の例は、for each nextループの使用方法を示しています:
例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
例2:
Sub DisplayArrayItems()
Dim myArray, item
myArray = Array("Apple", "Banana", "Cherry")
For Each item In myArray
'Each element of the array.
Next
End Sub
例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