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 EachObjectVar
InCollectionName
' 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 Sub
Thus, 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.
Get Access Database Design and Programming, Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.