The Do Loop
The Do
loop has several variations. To describe these variations, I use the notation:
{While | Until}
to represent either the word While
or the word Until
, but not both. With this in mind, here are the possible syntaxes for the Do
loop:
Do {While | Until} condition
' code block here
Loop
or:
Do
' code block here
Loop {While | Until} condition
Actually, there is a fifth possibility, because you can dispense with condition
completely and write:
Do ' code block here Loop
Some of these variations are actually quite subtle. For instance, the following code cycles through the paragraphs in the active document as long as the paragraphs have some characters in them (other than the end of paragraph mark):
' Set para to first paragraph Set para = ActiveDocument.Paragraphs(1) Do While para.Range.Characters.Count ' Code here ' Set para to next paragraph Loop
Consider also the following code, whose purpose is similar:
' Set para to first paragraph Set para = ActiveDocument.Paragraphs(1) Do ' Code here ' Set para to next paragraph Loop While para.Range.Characters.Count> 1
The difference between these two versions is that in the first case, the condition is checked immediately, before any code within the Do
loop is executed. Thus, if the first paragraph has no text (so it has only an ending paragraph mark), its character count will be 1 and the condition will fail. Thus, no code will be executed within the Do
loop.
On the other hand, in the second case, the condition is checked at the end ...
Get Writing Word Macros, Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.