Chapter 8. Control Statements

In this chapter:

  • The If … Then Statement

  • The For Loop

  • The For Each Loop

  • The Do Loop

  • The Select Case Statement

  • A Final Note on VBA

I conclude our discussion of the VBA language with a discussion of the main VBA control statements, which are statements that affect the flow of control (or flow of execution) in a program.

The If… Then Statement

The If…Then statement is used for conditional control. The syntax is:

	If Condition Then
	   ' statements go here . . .
	ElseIf AnotherCondition Then
	   ' more statements go here . . .
	Else
	   ' more statements go here . . .
	End If

Note that you may include more than one ElseIf part and that both the ElseIf part(s) and the Else part are optional. We can also squeeze all parts of this statement onto a single line, which is generally only a good idea when the ElseIf and Else parts are missing.

As an example, the following code deletes the current selection in the active Word document if it contains the word “Bartok”:

	Dim sText As String
	sText = Selection.Text
	If InStr(sText, "Bartok") Then Selection.Delete

The following example changes the font size of the selected text based upon its style. If the style is not Heading 1, Heading 2, or Heading 3, then the point size is set to 11 points:

	If Selection.Style = "Heading 1" Then
	   Selection.Font.Size = 24
	ElseIf Selection.Style = "Heading 2" Then
	   Selection.Font.Size = 18
	ElseIf Selection.Style = "Heading 3" Then
	   Selection.Font.Size = 14
	Else
	   Selection.Font.Size = 11
	End If

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.