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

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.