Crystal Reports Online Training

Learn Online, Anytime, Anywhere

Step-by-step online tutorials.

7.13 For Next Loop

Looping Structures

Looping structures let you execute a block of code multiple times. The number of times this code block is executed depends upon the type of loop used and what happens within the code block. The looping structures covered are: For Next, While, and a variety of Do loops.

For Next Loop

The For Next loop has the syntax of using the For statement followed by a variable and the start and ending range. You have to decide in advance how many times the code block gets executed.

The default loop increment is 1. Use the Step keyword to define a new increment. Terminate the For block using the Next statement. Putting the variable name after the Next statement is optional. You can prematurely exit the loop by using the Exit For statement.

Crystal syntax uses := to assign the loop range and it has the Do keyword at the end of the line. Rather than terminating the loop with the Next keyword, it requires parentheses to surround the code block.

For var := start To end Step increment Do
(
…code…
If condition Then
Exit For
End If
)

The next example uses a loop to summarize all the salary balances that were stored in a global array (which was populated elsewhere in the report).

//Demonstrate looping to calculate total salaries
NumberVar TotalSalary;
NumberVar ArrayIndex;
Global NumberVar Array Salaries;
For ArrayIndex:=1 to UBound(Salaries) Do
(
TotalSalary := TotalSalary + Salaries[ArrayIndex];
);