Navigation bar
  Start Previous page
 33 of 156 
Next page End 28 29 30 31 32 33 34 35 36 37 38  

27
The <exit-type> element may be Do, For, Sub or Function but the use of each is restricted to use
within a Do-Loop, For-Next, subroutine and function, respectively.  Any other use will result in a compiler
error.
Example
Do
    <other-statements>
    If (i > 5) Then
        Exit Do
    End If
    <other-statements>
Loop
When an Exit Do is executed within nested Do-Loop statements only the innermost Do-Loop that
contains the exit statement will be terminated.  Control will be transferred to the first statement following
the terminated Do-Loop.  The same idea applies to an Exit For within nested For-Next statements.
2.5.8 For-Next Statement
The For-Next compound statement is another form of looping that provides controlled iteration using a
loop index variable.  The syntax for a For-Next loop is:
For <var> = <start-expr> To <end-expr> [ Step <step-expr> ]
[<statements>]
Next [ <var> ]
The <var> element, referred to as the loop index variable, must refer to a previously defined scalar
variable (i.e. not an array element) that is either a numeric type or an enumeration type.  The <start-
expr>, <end-expr> and optional <step-expr> elements must all be the same type as the loop index
variable.
Example
Dim i as Integer
For i = 1 To 10
    Debug.Print CStr(i)
Next i
When the For statement begins execution, the <start-expr> is evaluated and the resulting value is
assigned to the loop index variable.  Then, before executing any statements contained within the body of
the For-Next statement, the <end-expr> is evaluated and the value of loop index variable is compared
to that value.  If the value of the loop index variable is less than or equal to the value of the <end-expr>
the statements within the body of the For-Next are executed.  This is called the “loop entry test” because
it controls whether or not the loop statements are executed.
At the bottom of the loop, marked by the Next statement, the loop index variable is modified in
preparation for the next iteration of the For-Next loop.  If the optional Step <step-expr> is present its
value is added to the loop index variable, otherwise the loop index variable is simply augmented by 1. 
Then control is transferred back to the top of the loop where the loop entry test is performed again.
 
The logic of the For loop in the example above may be exactly duplicated using other statements as
illustrated below.  You can see that the For loop allows you to express the same logic more concisely.
Previous page Top Next page