Microsoft Office Tutorials and References
In Depth Information
Understanding Objects and Collections
element is an object variable of the appropriate type for the collection,
collection is the name of a collection, and statements is any number of
statements to be executed within the loop.
Whether you ever need a For Each...Next loop in your own code
depends on how fancy your code gets. If you use other people’s code,
however, you may come across an occasional For Each...Next loop, so you
need to have an idea of what that loop does.
You may recall from “Referring to objects and collections,” earlier in this
chapter, that the AllForms collection in the CurrentProject object
contains all the forms in the current database. Each form in the collection is a
type of AccessObject.
The Forms collection contains only the forms that are open. The AllForms
collection includes both closed and open forms.
In Listing 4-5, the Dim statement declares an object variable named myForm
as an AccessObject. Then a For Each...Next loop loops through the
AllForms collections and prints the Name property of every form in the
Listing 4-5: Looping Through the AllForms Collection
Dim myForm as AccessObject
For Each myForm In CurrentProject.AllForms
‘Code to be performed on every form.
Debug.Print myForm.Name
Running the code in Listing 4-5 prints the name of each form in the current
database to the Immediate window.
A form is a collection in its own right — a collection of controls. To set up a
loop that looks at each control on a form, you first need to make sure that
the form is open. Then define an object variable as the Control element
type. The collection name used in the For Each...Next loop needs to be a
specific open form.
The code snippet in Listing 4-6 opens a form named Products Form. The
Dim statement creates an object variable, named myCtl, as the generic
Control type of object. The For Each...Next loop specifies all the controls
on the current form as the collection. With each pass through the loop in
Listing 4-6, the Debug.Print statement prints the name of the current
Search JabSto ::

Custom Search