|
For...Next Statements |
Format:
For counter = start To end [ Step step ]
[ statements ]
[ Exit For ]
[ statements ]
Next
Syntax:
Remarks:
1. If counter has not been declared outside this loop, you can declare it within the For statement.
2. The step argument can be either positive or negative.
3. The expressions start, end, and step are all evaluated only once, when the For statement is first encountered. They are not evaluated again, even if the loop statements change their constituent parts.
4. After the loop statements have executed, step is added to counter. At this point, the For statement again compares counter to end. As a result of this comparison, either the statements in the loop execute again, or the loop is terminated and execution continues with the statement following the Next statement.
5. Changing the value of counter while inside a loop can make it more difficult to read and debug your code.
6. The Exit For statement transfers control immediately to the statement following the Next statement. Any number of Exit For statements can be placed anywhere in the For...Next loop. Exit For is often used after evaluating some condition, for example with an If...Then...Else statement.
7. Loop executes if:
- step value is non zero
- start <= end and step > 0
- start > end and step < 0
Otherwise For statement is not executed.
8. You can nest For...Next loops by placing one loop within another. Each loop must have a unique counter variable. The following construction is correct:
For I = 1 To 10
For J = 1 To 10
For K = 1 To 10
' Statements to operate with current values of I, J, and K.
Next
Next
Next
See also:
- Exit statement
- Do...Loop statements
- While statements
Example:
For I = 1 To 10
For J = 1 To 10
For K = 1 To 10
Print "i=",i, ", j=",j, ", k=", k
num = Rnd*100 ' lets exit from for randomly
if num=50 then
Print "Exiting from for..."
Exit For
endif
Next
Next
Next
Copyright (c) 2000-2006 by Smartphoneware. All rights reserved.