The Select Case Statement

As we have seen, the If…Then construct is used to perform different tasks based on different possibilities. An alternative construct that is often more read-able is the Select Case statement, whose syntax is:

	Select Case testexpression
	   Case value1
	       ' statements to execute if testexpression = value1
	   Case value2
	       ' statements to execute if testexpression = value2
	   . . .

	   Case Else
	      ' statements to execute otherwise
	End Select

Note that the Case Else part is optional. To illustrate: the following code is the Select Case version of the earlier example (see the previous discussion of the If…Then statement) that changes the font size of different headings. I think you will agree that this is a bit more readable than the previous version:

	Select Case Selection.Style
	   Case "Heading 1"
	      Selection.Font.Size = 24
	   Case "Heading 2"
	      Selection.Font.Size = 18
	   Case "Heading 3"
	      Selection.Font.Size = 14
	   Case Else
	      Selection.Font.Size = 11
	End Select

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.