對於每個迴圈
For Each
迴圈結構非常適合迭代集合的所有元素。
Public Sub IterateCollection(ByVal items As Collection)
'For Each iterator must always be variant
Dim element As Variant
For Each element In items
'assumes element can be converted to a string
Debug.Print element
Next
End Sub
迭代物件集合時使用 For Each
:
Dim sheet As Worksheet
For Each sheet In ActiveWorkbook.Worksheets
Debug.Print sheet.Name
Next
迭代陣列時避免使用 For Each
; For
迴圈將為陣列提供明顯更好的效能。相反,在迭代 Collection
時,For Each
迴圈將提供更好的效能。
句法
For Each [item] In [collection]
[statements]
Next [item]
Next
關鍵字可以選擇後跟迭代器變數; 這可以幫助澄清巢狀迴圈,儘管有更好的方法來澄清巢狀程式碼,例如將內部迴圈提取到自己的過程中。
Dim book As Workbook
For Each book In Application.Workbooks
Debug.Print book.FullName
Dim sheet As Worksheet
For Each sheet In ActiveWorkbook.Worksheets
Debug.Print sheet.Name
Next sheet
Next book