VBA 迭代数组的元素
示例
For...Next
使用iterator变量作为索引号是迭代数组元素的最快方法:
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.Printitems(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.Printitems(outer, inner)
Next
NextForEach...Next
一个ForEach...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.Printitem
Next甲ForEach环将遍历从外到内的所有尺寸(相同的顺序的元素在存储器布局),故没有必要对嵌套循环:
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.Printitem
Next请注意,如果性能很重要,则ForEach循环最好用于迭代Collection对象。
上面的所有4个摘要均产生相同的输出:
0 1 2 3