• Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

13. Control Statements > 13.4. The For Each Loop

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 In CollectionName

   ' block of code goes here . . .

Next ObjectVar

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

PREVIEW

                                                                          

Not a subscriber?

Start A Free Trial


  
  • Creative Edge
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint