Microsoft Office Tutorials and References
In Depth Information
Executing the Same Code Repeatedly
Because Counter already has a value of 101 when the Do While Counter
< 100 statement executes, the looping condition is False right off the bat.
Thus, everything between the Do While and Loop statements is skipped
completely, and code execution resumes at the statements after the loop.
In the following code, the looping condition, While Counter < 100,
moves to the bottom of the loop:
Counter = 101
Do
Counter = Counter +1
Loop While Counter < 100
‘Statements below the loop.
In the preceding loop, Counter receives a value of 101. The Do
statement doesn’t specify a condition for starting the loop, so the Counter =
Counter + 1 statement within the loop executes. Then the Loop While
Counter < 100 condition proves to be False (because Counter = 102
by then), so code execution continues at the statements after the Loop
statement at the bottom of the loop.
In short, when you define the condition for the loop at the top of the loop, the
code within the loop may not execute at all, but if you define the condition at
the bottom of the loop, the code within the loop executes at least once.
Using While...Wend to create a loop
The While...Wend loop is similar to Do...Loop, but it uses the simpler
(and less flexible) syntax shown in the following code:
While condition
[statements]
Wend
condition is an expression that results in a True or False value, and
statements is any number of VBA statements, all of which execute with
each pass through the loop.
Book VIII
Chapter 3
The condition is evaluated at the top of the loop. If the condition proves to be
True, all lines within the loop execute (down to the Wend statement), and the
condition at the top of the loop is evaluated again. If the condition proves to
be False, all statements within the loop are ignored, and processing continues
at the first line after the Wend statement.
Using For...Next to create a loop
When you want to create a loop that keeps track of how many times the loop
repeats, you can use the For...Next block of statements. The syntax for a
For...Next loop is as follows:
 
Search JabSto ::




Custom Search