对于每个循环
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