迭代数组的元素

对于…下一页

使用迭代器变量作为索引号是迭代数组元素的最快方法:

Dim items As Variant
items = Array(0, 1, 2, 3)

Dim index As Integer
For index = LBound(items) To UBound(items)
    'assumes value can be implicitly converted to a String:
    Debug.Print items(index) 
Next

嵌套循环可用于迭代多维数组:

Dim items(0 To 1, 0 To 1) As Integer
items(0, 0) = 0
items(0, 1) = 1
items(1, 0) = 2
items(1, 1) = 3

Dim outer As Integer
Dim inner As Integer
For outer = LBound(items, 1) To UBound(items, 1)
    For inner = LBound(items, 2) To UBound(items, 2)
        'assumes value can be implicitly converted to a String:
        Debug.Print items(outer, inner)
    Next
Next

每个……下一个

如果性能无关紧要,For Each...Next 循环也可用于迭代数组:

Dim items As Variant
items = Array(0, 1, 2, 3)

Dim item As Variant 'must be variant
For Each item In items
    'assumes value can be implicitly converted to a String:
    Debug.Print item
Next

For Each 循环将迭代从外部到内部的所有维度(与在内存中布置元素的顺序相同),因此不需要嵌套循环:

Dim items(0 To 1, 0 To 1) As Integer
items(0, 0) = 0
items(1, 0) = 1
items(0, 1) = 2
items(1, 1) = 3

Dim item As Variant 'must be Variant
For Each item In items
    'assumes value can be implicitly converted to a String:
    Debug.Print item
Next

请注意,如果性能很重要,For Each 循环最好用于迭代 Collection 对象。

上面的所有 4 个片段产生相同的输出:

 0
 1
 2
 3