Siebel VB Language Reference > VB Language Reference >

For...Next Statement


This standard VB control structure repeats a series of program lines a fixed number of times.

Syntax

For counter = start To end [Step increment]

     statement_block

     [Exit For]

     statement_block

Next [counter]

Placeholder
Description

counter

A numeric variable for the loop counter

start

The initial value of the counter

end

The ending value of the counter

increment

The amount by which the counter is changed each time the loop is run; the default is 1

statement_block

the Basic functions, statements, or methods to be executed

Returns

Not applicable

Usage

The start and end values must be consistent with increment. If end is greater than start, increment must be positive. If end is less than start, increment must be negative. Siebel VB compares the sign of (start - end) with the sign of increment. If the signs are the same, and end does not equal start, the For...Next loop is started. If not, the loop is omitted in its entirety.

With a For...Next loop, the program lines following the For statement are executed until the Next statement is encountered. At this point, the Step amount is added to the counter and compared with the final value, end. If the beginning and ending values are the same, the loop executes once, regardless of the Step value. Otherwise, the Step value controls the loop as follows:

Step Value
Loop Execution

Positive

If counter is less than or equal to end, the Step value is added to counter. Control returns to the statement after the For statement and the process repeats. If counter is greater than end, the loop is exited; execution resumes with the statement following the Next statement.

Negative

The loop repeats until counter is less than end.

Zero

The loop repeats indefinitely.

Within the loop, the value of the counter should not be changed, as changing the counter makes programs more difficult to maintain and debug.

For...Next loops can be nested within one another. Each nested loop should be given a unique variable name as its counter. The Next statement for the inside loop must appear before the Next statement for the outside loop. The Exit For statement can be used as an alternative exit from For...Next loops.

If the variable is left out of a Next statement, the Next statement matches the most recent For statement. If a Next statement occurs prior to its corresponding For statement, Siebel VB returns an error message.

Multiple consecutive Next statements can be merged together. If this is done, the counters must appear with the innermost counter first and the outermost counter last. For example:

For i = 1 To 10
   
statement_block
   For j = 1 To 5
      statement_block
Next j, i

Example

For an example, read CSng Function.

See Also

Do...Loop Statement
Exit Statement
While...Wend Statement

Siebel VB Language Reference