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
Loopor:
Do
' code block here
Loop {While | Until} conditionActually, 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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access