HandsOn Using Nested Loops

1. Import the Employees table and Employees form from the Acc2003_ Chap02.mdb database available in the book's downloadable files. In the currently open database, choose File | Get External Data | Import. Specify the database filename (Acc2003_Chap02.mdb) and select the objects to import.

2. Switch to the Visual Basic Editor window and insert a new module.

3. In the module's Code window, enter the GetFormsAndControls procedure as shown below.

Sub GetFormsAndControls()

Dim accObj As AccessObject Dim myControl As Control

Set obj = CurrentProject.AllForms

For Each accObj In obj

Debug.Print accObj.Name & " — Form" If Not accObj.IsLoaded Then DoCmd.OpenForm accObj.Name

For Each myControl In Forms(accObj.Name).Controls Debug.Print Chr(9) & myControl.Name


DoCmd.Close End If

Next End Sub

The GetFormsAndControls procedure shown above uses two For Each. Next loops to print the name of each currently open form and its controls to the Immediate window. To enumerate through the form's controls, the form must be open. Notice the use of the IsLoaded function. The procedure will only open the form if it is not yet loaded. The control names are indented in the Immediate window thanks to the Chr(9) function. This is like pressing the Tab key once. To get the same result, you can replace Chr(9) with a VBA constant: vbTab.

After reading the names of the controls, the form is closed and the next form is processed in the same manner. The procedure ends when no more forms are found in the AllForms collection of CurrentProject.

Introduction to Access 2003 VBA Programming

0 0

Post a comment