使用 For Each...Next

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