使用 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