迭代陣列的元素
對於…下一頁
使用迭代器變數作為索引號是迭代陣列元素的最快方法:
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