For Each...Next 사용

For Each...Next 루프는 For...Next 루프와 같습니다. 지정된 횟수만큼 명령문을 반복하는 대신 For Each...Next 루프는 객체 모음의 각 항목 또는 배열의 각 요소에 대해 명령문 그룹을 반복합니다. 이는 컬렉션에 있는 요소 수를 모르는 경우에 특히 유용합니다.

다음 예에서는 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