O'Reilly logo

Writing Word Macros, Second Edition by Steven Roman PhD

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required