beautypg.com

Campbell Scientific CR5000 Measurement and Control Module User Manual

Page 214

background image

Section 9. Program Control Instructions

9-8

Exit For

Only used within a For...Next control structure to provide
an alternate way to exit. Any number of Exit For
statements may be placed anywhere in the For...Next loop.
Often used with the evaluation of some condition (for
example, If...Then), Exit For transfers control to the
statement immediately following the Next.

Next

Ends a For...Next loop. Causes increment to be added to
counter.

The Step value controls loop execution as follows:

When Step is

Loop executes if

Positive or 0

counter <= end

Negative

counter >= end

Once the loop has been entered and all the statements in the loop have
executed, Step is added to counter. At this point, either the statements in the
loop execute again (based on the same test that caused the loop to execute in
the first place), or the loop is exited and execution continues with the statement
following the Next statement.

Tip

Changing the value of counter while inside a loop can make the

program more difficult to read and debug.

You can nest For...Next loops by placing one For...Next loop within another.
Give each loop a unique variable name as its counter. The following
construction is correct:

For I = 1 To 10

For J = 1 To 10

For K = 1 To 10

...

Next K

Next J

Next I

Note

If you omit the variable in a Next statement, the value of Step
increment is added to the variable associated with the most recent
For statement. If a Next statement is encountered before its
corresponding For statement, an error occurs.

For...Next Statement Example

The example runs one For..Next loop inside another.

Dim I, J 'Declare variables.
For J = 5 To 1 Step -1

'Loop 5 times backwards.

For I = 1 To 12

'Loop 12 times.

. . . .

'Run some code.

Next I
. . . .

'Run some code.

Next J
. . . .

'Run some code.

This next example fills odd elements of X up to 40 * Y with odd numbers.

For I = 1 To 40 * Y Step 2
X( I ) = I
Next I