Do For Iteration Statements

58

2.13.3.1 Do

The Do loop executes a block of statements either until a condition becomes true or while a condition remains true. The condition can be tested at the beginning or at the end of each iteration. If the test is performed at the end of each iteration, the block of statements is guaranteed to execute at least once. The Do loop can also be written without any conditions, in which case it executes repeatedly until and unless an Exit Do statement is executed within the body of the loop. Here are some examples of Do loops: Do While i 10 ... Loop Do Until i = 10 ... Loop Do ... Loop While i 10 Do ... Loop Until i = 10 Do ... Loop

2.13.3.2 For

The For loop executes a block of statements a specified number of times. The number of iterations is controlled by a loop variable, which is initialized to a certain value by the For statement, then is incremented for each iteration of the loop. The statements in the body of the loop are repeatedly executed until the loop variable exceeds a given upper bound. The syntax of the For loop is: For variable = expression To expression [ Step expression ] statements Next [ variable_list ] The loop variable can be of any numeric type. The variable is set equal to the value of the first expression before entering the first iteration of the loop body. Prior to executing each iteration of the loop, the loop variable is compared with the value of the second expression. If the value of the loop variable is greater than the expression or less than the expression if the step expression is negative, the loop exits and execution continues with the first statement following the Next statement. The step expression is a numeric value that is added to the loop variable between loop iterations. If the Step clause is omitted, the step expression is taken to be 1 . The Next statement marks the end of the loop body. The Next keyword can either appear by itself in the statement or be followed by the name of the loop variable. If For statements are nested, a single Next statement can terminate the bodies of multiple loops. For example: For i = 1 To 10 For j = 1 To 10 59 For k = 1 To 10 ... Next k, j, I This code is equivalent to the following: For i = 1 To 10 For j = 1 To 10 For k = 1 To 10 ... Next Next Next I recommend the latter style, since it is considered more structured to terminate each block explicitly. It is interesting to note that the For loop is equivalent to the following Do loop construction assuming that step_expression is nonnegative: loop_variable = from_expression Do While loop_variable = to_expression statements loop_variable += step_expression Loop If step_expression is negative, the For loop is equivalent to this only the comparison in the Do statement is different: loop_variable = from_expression Do While loop_variable = to_expression statements loop_variable += step_expression Loop

2.13.3.3 For Each