Product help with community knowledge

### Page statistics

885 views1 edit(s)4163 characters(s) Page last modified 18:12, 12 Apr 2012 by contentconnector

# For...Next Statement

A For...Next statement iterates according to supplied lower and upper bound values.

A For statement specifies the following:

• Loop control variable
• Lower bound expression
• Upper bound expression
• Optional step value expression

A For statement must be closed by a matching Next statement

The following syntax applies to For...Next statements.

```For <identifier> = <LowerBoundExpression > To <UpperBoundExpression> [Step expression]
[statements]
Next [identifier]```

The identifier specifies the loop control variable, and must be declared prior to the For statement, either as type Integer or Number. Nested For...Next statements must each use their own loop control variable.

At the beginning of the loop, the lower bound expression is assigned to the loop control value. An optional Step value sets the amount by which the loop control variable will change with each iteration. If no Step value is provided, a default value of 1 is used. At the Next statement, the value of the loop control value increases or decreases by the amount of the step value.

The upper bound, lower bound, and step expressions are computed once, at the beginning of the loop.

At the beginning of each iteration, the loop control variable is compared to see if it is greater or less than the upper bound expression (depending on a positive or negative Step value). If the control variable exceeds the upper bound, the loop terminates; otherwise the statement block is executed..

The following example shows a For...Next loop with a specified Step value of 2.

```Rule total As Integer
Dim counter As Integer = 0

For counter = 0 To 10 Step 2
total = total + counter
printValue("Total = " + stringValue(total) + _
" Counter = " + stringValue(counter))
Next
End Rule
Output:
"Total = 0 Counter = 0"
"Total = 2 Counter = 2"
"Total = 6 Counter = 4"
"Total = 12 Counter = 6"
"Total = 20 Counter = 8"
"Total = 30 Counter = 10"```

You can exit a For...Next loop by using an Exit For statement in the body of the loop.