The For Each Loop
The For
Each loop is a
variation on the For loop that was designed to
iterate through a collection of objects (as well as through elements
in an array), and is generally much more efficient than using the
traditional For loop. The general syntax is:
For EachObjectVarInCollectionName' block of code goes here . . . NextObjectVar
where ObjectVar is a variable of the same object
type as the objects within the collection. The code block will
execute once for each object in the collection.
The following version of PrintFields uses a
For
Each loop. It is more
elegant than the previous version (and more efficient as well):
Sub PrintFields2()
Dim fld As Field
Dim rs As Recordset
Set rs = CurrentDb.OpenRecordset("Objects")
For Each fld In rs.Fields
Debug.Print fld.Name
Next
rs.Close
End SubThus, when iterating through a collection of objects, we have two choices:
For Each object in Collection ' code block here Next object
or:
For i = 1 to Collection.Count ' code block here Next i
It is important to keep in mind that the For
Each loop can be much faster than the
For loop when dealing with collections of objects.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access