Please enable JavaScript to view this site.

 

Navigation: Macros > Macro Language > Instructions > Looping

Looping with the  FOR  Keyword

Scroll Prev Up Next More

The for-to-step instruction repeats a block of instructions, adding the step to the counter after each iteration. A positive step increases the counter; a negative step decreases it.

 

➢The for loop is used when you want to iterate through some values and you know, before entering the loop, what the range will be. If the concept of a counter moving through a range does not seem suited to your problem, try the while loop.

 

Before the block to be repeated, place a for-to-step statement. It specifies an integer counter variable, a starting value, an ending value, and an optional step. These values must be integer expressions. If step is omitted, its value defaults to 1. A step of zero causes an error.

for nCounter = nStartVal to nEndVal step nStepVal

The counter starts at nStartVal. With a positive step, the loop executes while the counter is less than or equal to nEndVal. With a negative step, it executes while the counter is greater than or equal to nEndVal. The ending value is included if the counter reaches it. If the starting value is already beyond the ending value in the direction of the step, the loop is not entered, as in the following example:

 for nX = 3 to 2 step 1 // this will go nowhere !

The block finishes at endfor. The step nStepVal is then added to nCounter, and the boundary is tested again. If the counter is still within the boundary for the direction of the step, the block is performed once more.

 

➢If you try to change any the values used in the 3 expressions of the for statement, within the loop, the compiler will generate an error message.

 

A for loop can always be replaced by a while loop.

for nDate = nToday to nJanOneNextYear step 7
   // do something on each selected date
endfor

However, the use of a for loop, when appropriate makes code much more legible, as we can see if we consider the replacement of the above for loop by the while loop below.

nDate = nToday
while nDate <= nJanOneNextYear
   // do something on each selected date
   nDate = nDate + 7
endwhile

To interrupt the flow of a for loop, use the break or continue commands.

 

See also: while loops.

 


Topic 105145, last updated on 09-Oct-2026