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 For Loop

The For…Next statement provides a method for repeatedly looping through a block of code (that is, one or more lines of code). This loop is naturally referred to as a For loop. The basic syntax is:

	For counter = start To end
	   ' block of code goes here . . .
	Next counter

The first time that the block of code is executed, the variable counter (called the loop variable for the For loop) is given the value start. Each subsequent time that the block of code is executed, the loop variable counter is incremented by 1. When counter exceeds the value end, the block of code is no longer executed. Thus, the code block is executed a total of end– start + 1 times, each time with a different value of counter.

Note that we can omit the word counter in the last line of a For loop (replacing Next counter with just Next). This may cause the For loop to execute a bit more quickly, but it also detracts a bit from readability.

For example, the following code loops through the collection of all paragraphs in the active Word document. (I discuss collections at length in Chapter 9, Object Models.) If the paragraph has style Heading 1, the style is changed to Heading 2:

	Dim i As Integer
	Dim para As Paragraph

	For i = 1 To ActiveDocument.Paragraphs.Count
	   ' Get the next paragraph
	   Set para = ActiveDocument.Paragraphs(i)
	   ' Change style from Heading 1 to Heading 2
	   If para.Style = "Heading 1" Then
	      para.Style = "Heading 2"
	   End If

	Next i

For loops are often used to initialize an array. For instance, the code: ...

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