ACC: How to Create For Next Loops in a MacroID: Q90815
|
To perform a For Next loop in a Microsoft Access macro, you need to
use a combination of correct macro structure and the RunMacro action
with appropriate information supplied in either the Repeat Count or
Repeat Expression parameters.
To enhance your macro, you can use a different macro structure and
include a call to an Access Basic function that maintains a
counter, or use the SetValue macro action to maintain and update a
counter value in a text box on a hidden form. The benefit of
maintaining a counter is that you can use the value of the counter in
your macro processing just as in a Access Basic For Next loop.
To perform a For Next loop in a macro, you would use a macro similar to the following examples. To create the following sample macros, open a new macro and choose Macro Names from the View menu. Add the following macro names and actions, then save this macro group as "For_Next_Loops".
Macro Name Action
-------------------------
For_Next_Loop1 RunMacro
Loop1 MsgBox
For_Next_Loop1 Actions
----------------------------------
RunMacro
MacroName: For_Next_Loops.Loop1
Repeat Count: 10
Loop1 Actions
-------------------
MsgBox
Message: ="Loop"
Macro Name Action
-------------------------
For_Next_Loop2 SetValue
RunMacro
Loop3 MsgBox
SetValue
For_Next_Loop2 Actions
----------------------
SetValue
Item: Forms![CounterForm]![Counter]
Expression: 1
RunMacro
MacroName: For_Next_Loops.Loop2
Repeat Expression: Forms![CounterForm]![Counter]<=10
Loop2 Actions
-------------------
MsgBox
Message: ="Loop Count: " & Forms![CounterForm]![Counter]
SetValue
Item: Forms![CounterForm]![Counter]
Expression: Forms![CounterForm]![Counter]+1
Macro Name Action
-------------------------
For_Next_Loop3 RunCode
RunMacro
Loop3 MsgBox
RunCode
For_Next_Loop3 Actions
--------------------------------------
RunCode
Function Name: =LoopCount(1)
RunMacro
MacroName: For_Next_Loops.Loop3
Repeat Expression: LoopCount(3)<=10
Loop3 Actions
-----------------------------------------
MsgBox
Message: ="Loop Count: " & LoopCount(3)
RunCode
Function Name: =LoopCount(2)
Function LoopCount (Action)
Static LoopCounter ' Static variable to hold counter
If Action = 1 Then ' Initialize counter
LoopCounter = 0
ElseIf Action = 2 Then ' Increment counter
LoopCounter = LoopCounter + 1
End If
LoopCount = LoopCounter ' Return value
End Function
Microsoft Access "Introduction to Programming," version 1.0, chapter 3,
pages 6-7 and 10-11
Microsoft Access "Language Reference," version 1.0, pages 246-248,
316-317, 412-414, and 437-438
Keywords : kbusage McrOthr
Version : 1.0 1.10 2.0
Platform : WINDOWS
Issue type : kbhowto
Last Reviewed: March 11, 1999