BUY THIS BOOK
Add to Cart

Print Book $44.99


Safari Books Online

What is this?

Add to UK Cart

Print Book £24.95

What is this?

Looking to Reprint this content?


Writing Word Macros
Writing Word Macros, Second Edition An Introduction to Programming Word using VBA By Steven Roman, Ph.D.
October 1999
Pages: 410

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: Introduction
In this chapter:
  • Program Example: Creating Tables
  • Program Example: Shortcut Key Assignments
  • Program Example: User Interaction
  • Elements of Word VBA Programming
Microsoft Word is a word processor of enormous power and flexibility. But despite its powerful feature set, there is a great deal that Word either does not allow you to do or does not allow you to do easily through its user interface. In these cases, we must turn to Word programming.
Let me give you two examples. I can assure you that these are real-life examples, because they happened to me.
In writing this book, I was faced with the problem of turning long columns of words into tables. Word's built-in ConvertToTable command was not flexible enough for my needs for three reasons.
First, I wanted the items to be placed in the table in column-major order (the first column is filled first) rather than in row-major order (the first row is filled first). Second, I wanted to choose the number of columns based on the number of words (cells), so I needed to know the word count before I made the choice of the number of columns. Finally, I wanted a row at the top of the table for a title.
To illustrate, I wanted to be able to select the following column of words:
Border
Cell
Column
Document
Font
Options
PageSetup
Paragraph
ParagraphFormat
Range
Row
Selection
Style
Table
Template
Window
and be presented with a dialog box similar to the one shown in . Then, if I entered 3 for the number of columns and hit the OK button, I wanted Word to automatically construct for me.
Figure : Table-making dialog box
Table : Table in Column-Major Order
Table
Border
PageSetup
Style
Cell
Paragraph
Table
Column
ParagraphFormat
Template
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Preliminaries
In this chapter:
  • What Is a Programming Language?
  • Programming Style
We begin with some general facts related to programming and programming languages to give the main subject matter of this book some perspective. After all, VBA is just one of many programming languages and anyone who wants to be a VBA programmer should have some perspective on where VBA fits into the greater scheme of things. Rest assured, however, that we will not dwell on side issues. The purpose of this chapter is to give a brief overview of programming and programming languages that will be of interest to readers who have not had any programming experience, as well as to those who have.
Simply put, a programming language is a very special and very restricted language that is understood by the computer at some level. We can roughly divide programming languages into three groups, based on the purpose of the language:
  • Languages designed to manipulate the computer at a low level—that is, to manipulate the operating system (Windows or DOS) or even the hardware itself—are called low-level languages. An example is assembly language.
  • Languages designed to create standalone applications, such as Microsoft Word itself, are high-level languages. Examples are BASIC, COBOL, FORTRAN, C, C++, and Visual Basic.
  • Languages that are designed to manipulate an application program, such as Microsoft Word, are application-level languages. Examples are Word VBA, Excel VBA, and PowerPoint VBA, each of which is a different form of VBA, designed to manipulate a different application.
These terms are not set in concrete and may be used differently by others. However, no one would disagree with the fact that some languages are intended to be used at a lower level than others.
The computer world is full of programming languages—hundreds of them. In some cases, languages are developed for specific computers. In other cases, languages are developed for specific types of applications. gives some examples of programming languages and their general purposes.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
What Is a Programming Language?
Simply put, a programming language is a very special and very restricted language that is understood by the computer at some level. We can roughly divide programming languages into three groups, based on the purpose of the language:
  • Languages designed to manipulate the computer at a low level—that is, to manipulate the operating system (Windows or DOS) or even the hardware itself—are called low-level languages. An example is assembly language.
  • Languages designed to create standalone applications, such as Microsoft Word itself, are high-level languages. Examples are BASIC, COBOL, FORTRAN, C, C++, and Visual Basic.
  • Languages that are designed to manipulate an application program, such as Microsoft Word, are application-level languages. Examples are Word VBA, Excel VBA, and PowerPoint VBA, each of which is a different form of VBA, designed to manipulate a different application.
These terms are not set in concrete and may be used differently by others. However, no one would disagree with the fact that some languages are intended to be used at a lower level than others.
The computer world is full of programming languages—hundreds of them. In some cases, languages are developed for specific computers. In other cases, languages are developed for specific types of applications. gives some examples of programming languages and their general purposes.
Table : Some Programming Languages
Language
General Purpose
BASIC
A simple, easy-to-learn language designed for beginners
Visual Basic
A version of BASIC designed for creating Windows applications
C, C++
Very powerful languages with excellent speed and control over the computer
Visual C++
A version of C++ designed for creating Windows applications
Pascal
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Programming Style
The issue of what constitutes good programming style is, of course, subjective, just as is the issue of what constitutes good writing style. Probably the best way to learn good programming style is to learn by example and to keep the issue somewhere in your consciousness while programming.
This is not the place to enter into a detailed discussion of programming style. However, in my opinion, the two most important maxims for good programming are:
  • Fill your programs with a lot of meaningful comments.
  • When in doubt, favor readability over cleverness or elegance.
It is impossible to overstate the importance of adding meaningful comments to your programs—at least any program with more than a few lines.
The problem is this: good programs are generally used many times during a reasonably long lifetime, which may be measured in months or even years. Inevitably, a programmer will want to return to his or her code to make changes (such as adding additional features) or to fix bugs (errors). However, despite all efforts, programming languages are not as easy to read as spoken languages. It is just as inevitable that a programmer will not understand (or perhaps even recognize!) code that was written several months or years earlier and must rely on carefully written comments to help reacquaint himself with his own code. (This has happened to me more times that I care to recall.)
Let me emphasize that commenting code is almost as much of an art as writing the code itself. I have often seen comments similar to the following:
	' Set x equal to 5
	x = 5
This comment is pretty useless, because the actual code is self-explanatory. It simply wastes time and space. (In a teaching tool, such as this book, you may find some comments that would otherwise be left out of a professionally written program.)
An interesting test of the quality of your comments is to read just the comments (not the code) to see if you get a good sense not only of what the program is designed to do, but also of the steps that are used to accomplish the program's goal. For example, here are the comments from the BASIC program shown in :
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: The Visual Basic Editor, Part I
In this chapter:
  • The Project Window
  • The Properties Window
  • The Code Window
  • The Immediate Window
  • Arranging Windows
  • Document Events
The first step in becoming a Word VBA programmer is to become familiar with the environment in which Word VBA programming is done. Each of the main Office applications has a programming environment referred to as its Integrated Development Environment or IDE. Microsoft also refers to this programming environment as the Visual Basic Editor.
My plan in this chapter and the next is to describe the major components of the Word IDE. I realize that you are probably anxious to get to some actual programming, but it is necessary to gain some familiarity with the IDE before you can use it. Nevertheless, you may want to read quickly through this chapter and the next and then refer to them as needed.
The Word, Excel, and PowerPoint IDEs have the same appearance, shown in . (The Microsoft Access IDE has a different appearance.) To start the Word IDE, simply choose Visual Basic Editor from the Macros submenu of the Tools menu or press Alt-F11.
The window in the upper-left corner of the client area (below the toolbar) is called the Project Explorer. shows a close-up of this window.
Note that the Project Explorer has a treelike structure, similar to the Windows Explorer's folders pane (the lefthand pane). Each entry in the Project Explorer is called a node. The top nodes, of which there are three in , represent the currently open Word VBA projects (hence the name Project Explorer). The view of each project can be expanded or contracted by clicking on the small boxes (just as with Windows Explorer). In particular, there is one project for each open document and each attached template. There is also a project for the Normal template and for any other attached global templates.
Figure : The Word VBA IDE
Figure :
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Project Window
The window in the upper-left corner of the client area (below the toolbar) is called the Project Explorer. shows a close-up of this window.
Note that the Project Explorer has a treelike structure, similar to the Windows Explorer's folders pane (the lefthand pane). Each entry in the Project Explorer is called a node. The top nodes, of which there are three in , represent the currently open Word VBA projects (hence the name Project Explorer). The view of each project can be expanded or contracted by clicking on the small boxes (just as with Windows Explorer). In particular, there is one project for each open document and each attached template. There is also a project for the Normal template and for any other attached global templates.
Figure : The Word VBA IDE
Figure : The Project Explorer
Each project has a name, which the programmer can choose. The default name for a project related to a document is Project. The default name for a project related to a template is TemplateProject. The top node for each project is labeled:
            ProjectName (DocumentName)
          
where ProjectName is the name of the project and DocumentName is the name of the document or template.
For instance, the active document at the time that was created is the manuscript for this book and is named Word.doc. Since I never changed the default project name, there is a node in labeled:
	Project (Word)
Since Word.doc is based on the template CSBOOKS.DOT (which I use for writing computer science books), there is also a node labeled:
	TemplateProject (CSBOOKS)
In general, each project may contain one of several different types of objects: Document objects, standard modules, class modules, UserForm objects, and references. I discuss each of these types of objects later in this section.
First, note that two of the objects that can make up a project—the Document object and the UserForm object—can themselves have two components: a code component, consisting of any code that is associated with the object, and a visual interface (also called a user interface), which is the component that is visible to the user and with which the user interacts. On the other hand, standard modules and class modules have only a code component, with no visual interface.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Properties Window
The Properties window (see ) displays the properties of an object and allows us to change these properties.
When a standard module is selected in the Project window, the only property that appears in the Properties window is the module's name. However, when a document is selected in the Projects window, many of the document's properties appear in the Properties window, as shown in .
The Properties window can be used to change some of the properties of the object while no code is running—that is, at design time. Note, however, that some properties are read-only and cannot be changed. Other properties can be changed only by code, that is, at run time. Such properties generally do not appear in the Properties window.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Code Window
The Code window displays the code that is associated with the selected item in the Project window. To view this code, select the item in the Projects window and either choose Code from the View menu or hit the F7 function key. Alternatively, just double-click on the item in the Projects window.
Generally, a code module (standard, class, or UserForm) contains more than one procedure. The IDE offers the choice between viewing one procedure at a time (called procedure view) or all procedures at one time (called full-module view), with a horizontal line separating the procedures. Each view has its advantages and disadvantages, and you will probably want to use both views at different times. Unfortunately, Microsoft does not seem to have supplied a menu choice for selecting the view. To change views, click on the small buttons in the lower-left corner of the Code window. (The default view can be set using the Editor tab of the Options dialog box.)
Figure : The Properties window
Incidentally, the default font for the module window is Courier, which has a rather thin-looking appearance and may be somewhat difficult to read. You may want to change the font to FixedSys (on the Editor Format tab of the Options dialog box, under the Tools menu), which is very readable.
At the top of the Code window are two drop-down list boxes (see ). The Object box contains a list of the objects (such as forms and controls) that are associated with the current project, and the Procedure box contains a list of all of the procedures associated with the object selected in the Object box. The precise contents of these boxes vary depending on the type of object selected in the Project Explorer.

A Document object

When a document (ThisDocument) is selected in the Project window, the Object box contains only two entries: General, for general procedures, and Document. When Document is selected, the Procedure box contains empty code shells for the three events mentioned earlier (Open, Close, and New). For example, the Open code shell is:
	Private Sub Document_Open()

	End Sub

A standard module

Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Immediate Window
The Immediate window (see ) has two main functions. First, we can send output to this window using the command:
	Debug.Print
For instance, the code:
	Debug.Print ActiveWindow.Selection.Range.Text
will print whatever text is currently selected in the active window to the Immediate window. For instance, shows what happened when I selected the words "whatever text is currently selected" in the previous sentence and then ran the procedure shown in the Code window of . We can see the result in the Immediate window. This provides a nice way to experiment with different code snippets.
Figure : The Immediate window
The other main function of the Immediate window is to execute commands. For instance, by selecting some text in the active document, switching to the Immediate window, and entering the line shown in , the selected text will be boldfaced (after pressing the Enter key to execute the code).
Figure : The Immediate window: command execution
The Immediate window is an extremely valuable tool for debugging (finding errors in) a program, and you will probably use it often (as I do).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Arranging Windows
If you need more space for writing code, you can close the Properties window, the Project window, and the Immediate window. On the other hand, if you are fortunate to have a large monitor, then you can split your screen as shown in in order to see the Word VBA IDE and a Word document at the same time. Then you can trace through each line of your code and watch the results in the document! (You can toggle between Word and the IDE using the Alt-F11 function key combination.)
Figure : A split-screen approach
Many of the windows in the IDE (including the Project, Properties, and Immediate windows) can be in one of two states: docked or floating. This state can be set using the Docking tab on the Options dialog box shown in .
A docked window is one that is attached, or anchored, to an edge of another window or to one edge of the client area of the main VBA window. When a dockable window is moved, it snaps to an anchored position. On the other hand, a floating window can be placed anywhere on the screen.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Document Events
As we have discussed, each Word document has three events associated with it: Open, Close, and New. Any code that we place in the event procedure for one of these events will execute when the event occurs (or fires, as programmers say). To experiment with these events and when they fire, we can add the code shown in to each event. (This is a very handy trick for events that are associated with controls on a user form, as well.)
Figure : The docking options
Figure : Illustrating the document events
As you will see in the next chapter, the MsgBox command displays a simple dialog box containing some text on the screen.
To follow along, you should first select the ThisDocument node for a Word document in the Project window (don't forget to double-click on the node to open the corresponding code window, or use the F7 key). Then select Document in the Object box and each of Close, New, and Open in turn in the Procedure box. For each event, type in the single line of code that you see in . Then repeat the process with the TemplateProject that the document is based upon. However, change the code slightly by replacing the word "Document" with "Template", as in:
	MsgBox "Template close event fired."
Now close the active document. You should see two message boxes in succession. The first dialog box (see ) indicates that the template's Close event has fired, and the second one (see ) indicates that the document's Close event has fired. (Thus, the template event fires before the document event.)
Figure : Message box opened by the template's Document_Close event procedure
Figure : Message box opened by the document's Document_Close event procedure
If you now reopen the document, two message boxes will be displayed indicating that the template Open event is fired, followed by the document Open event. Note that the New event fires only when it is part of a template project (not a document project) and a new document based on that template is opened.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 4: The Visual Basic Editor, Part II
In this chapter:
  • Navigating the IDE
  • Getting Help
  • Creating a Procedure
  • Run Mode, Design Mode, and Break Mode
  • Errors
  • Debugging
  • Macros
In this chapter, I conclude discussion of the Visual Basic Editor by moving from its basic organization to a discussion of how you use the Editor when programming. Again, you may want to read quickly through this chapter and refer to it later as needed.
If you prefer the keyboard to the mouse (as I do), then you might want to use keyboard navigating shortcuts. Here are some tips.
The following keyboard shortcuts are used for navigating the IDE:
F7
Go to the Code window
F4
Go to the Properties window
Ctrl-R
Go to the Project window
Ctrl-G
Go to the Immediate window
Alt-F11
Toggle between Word and VB IDE
Within the code window, the following keystrokes are very useful:
F1 Help on the item under the cursor.
Shift-F2
Go to the definition of the item under the cursor. (If the cursor is over a call to a function or subroutine, pressing Shift-F2 sends you to the definition of that procedure.)
Ctrl-Shift-F2
Return to the last position where editing took place.
The following keystrokes are useful when tracing through code (discussed later):
F8 Step Into
Shift-F8
Step Over
Ctrl-Shift-F8
Step Out
Ctrl-F8
Run To Cursor
F5 Run
Ctrl-Break
Break
Shift-F9
Quick Watch
F9 Toggle Breakpoint
Ctrl-Shift-F9
Clear All Breakpoints
It is also possible to insert bookmarks within code. A bookmark marks a location to which you can return easily. To insert a bookmark, or to move to the next or previous bookmark, use the Bookmarks submenu on the Edit menu. The presence of a bookmark is indicated by a small blue square in the left margin of the code.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Navigating the IDE
If you prefer the keyboard to the mouse (as I do), then you might want to use keyboard navigating shortcuts. Here are some tips.
The following keyboard shortcuts are used for navigating the IDE:
F7
Go to the Code window
F4
Go to the Properties window
Ctrl-R
Go to the Project window
Ctrl-G
Go to the Immediate window
Alt-F11
Toggle between Word and VB IDE
Within the code window, the following keystrokes are very useful:
F1 Help on the item under the cursor.
Shift-F2
Go to the definition of the item under the cursor. (If the cursor is over a call to a function or subroutine, pressing Shift-F2 sends you to the definition of that procedure.)
Ctrl-Shift-F2
Return to the last position where editing took place.
The following keystrokes are useful when tracing through code (discussed later):
F8 Step Into
Shift-F8
Step Over
Ctrl-Shift-F8
Step Out
Ctrl-F8
Run To Cursor
F5 Run
Ctrl-Break
Break
Shift-F9
Quick Watch
F9 Toggle Breakpoint
Ctrl-Shift-F9
Clear All Breakpoints
It is also possible to insert bookmarks within code. A bookmark marks a location to which you can return easily. To insert a bookmark, or to move to the next or previous bookmark, use the Bookmarks submenu on the Edit menu. The presence of a bookmark is indicated by a small blue square in the left margin of the code.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Getting Help
If you are like me, you will probably make extensive use of Microsoft's Word VBA help files while programming. The simplest way to get help on an item is to place the cursor on that item and press the F1 key. This works not only for VBA language keywords but also for portions of the VBA IDE.
Note that Microsoft provides multiple help files for Word, the VBA language, and the Word object model. While this is quite reasonable, occasionally the help system gets a bit confused and refuses to display the correct help file when you hit the F1 key. (I have not found a simple resolution to this problem, other than shutting down Word and the Visual Basic Editor along with it!)
Note also that a standard installation of Microsoft Office does not install the VBA help files for the various applications. Thus, you may need to run the Office setup program and install Word VBA help by selecting that option in the appropriate setup dialog box. (Do not confuse Word help with Word VBA help.)
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Creating a Procedure
There are two ways to create a new procedure (subroutine or function) within a code module. First, after selecting the correct project in the Project Explorer, we can select the Procedure option from the Insert menu. This will produce the dialog box shown in . Just type the name of the procedure and select Sub or Function. (The Property choice is used with custom objects in a class module.) I discuss the issue of public versus private procedures and static variables later in this chapter.
Figure : The Add Procedure dialog box
A simpler alternative is to simply begin typing:
	Sub SubName
or:
	Function FunctionName
in any code window (following the current EndSub or EndFunction statement) or in the General window. As soon as you press the Enter key, Word will move the line of code to a new location and thereby create a new subroutine. (It will even add the appropriate ending—End Sub or End Function.)
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Run Mode, Design Mode, and Break Mode
The VBA IDE can be in any one of three modes: run mode, break mode, or design mode. The IDE is in design mode when you are writing code or designing a form.
Run mode occurs when a procedure is running. To run (or execute) a procedure, just place the cursor anywhere within the procedure code and hit the F5 key (or select Run from the Run menu). If a running procedure seems to be hanging, you can usually stop the procedure by hitting Ctrl-Break (hold down the Control key and hit the Break key).
Break mode is entered when a running procedure stops because of either an error in the code or a deliberate act on your part (described later in this chapter). In particular, if an error occurs, Word will stop execution and display an error dialog box with an error message, an example of which is shown in .
Figure : An error message
Error dialog boxes offer a few options: end the procedure, get help (such as it may be) with the problem, or enter break mode to debug the code. In the latter case, Word will stop execution of the procedure at the offending code and highlight that code in yellow. (I discuss the process of debugging code in the "Debugging" section later in this chapter.)
Aside from encountering an error, there are several ways we can deliberately enter break mode for debugging purposes:
  • Hit Ctrl-Break and choose Debug from the resulting dialog box.
  • Include a Stop statement in the code, which causes Word to enter break mode.
  • Insert a breakpoint on an existing line of executable code. This is done by placing the cursor on that line and hitting the F9 key (or using the Debug menu). Word will place a red dot in the left margin in front of that line and will stop execution when it reaches the line. You may enter more than one breakpoint in a procedure. This is generally preferred to using the Stop statement, because breakpoints are automatically removed when you close down the Visual Basic Editor, so you don't need to remember to remove them, as you do with Stop statements.
  • Set a watch statement that causes Word to enter break mode if a certain condition becomes true. (I discuss watch expressions later in this chapter.)
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Errors
In computer jargon, an error is referred to as a bug. Errors can be grouped into three types based on when they occur—design time, compile time, or run time.
As the name implies, a design-time error occurs during the writing of code. Perhaps the nicest feature of the Visual Basic Editor is that it can be instructed to watch as we type code and stop us when we make a syntax error. This automatic syntax checking can be enabled or disabled in the Options dialog box shown in , but I strongly suggest that you keep it enabled.
Notice also that there are other settings related to the design-time environment, such as how far to indent code in response to the Tab key.
Figure : The Options dialog box
To illustrate automatic syntax checking, shows what happens when we deliberately enter the syntactically incorrect statement x == 5 and then attempt to move to another line. Note that Microsoft refers to this type of error as a compile error in the dialog box, and perhaps we should as well. However, it seems more descriptive to call it a design-time error or just a syntax error.
Figure : A syntax error message
Before a program can be executed, it must be compiled, or translated into a language that the computer can understand. (This is not the place to go into a detailed discussion of compilation.) The compilation process occurs automatically when we request that a program be executed. We can also specifically request compilation by choosing the Compile Project item under the Debug menu.
If Word encounters an error while compiling code, it displays a compile error message. For example, the code in contains a compile-time error. In particular, the first line:
	Dim doc As Document
defines a variable of type Document to represent a Word document. (I will discuss all of this at the appropriate time, so don't worry about the details now.) However, the second line:
	Set doc = ActiveDocument.Name
attempts to assign the variable doc not to the active document (which would be legal), but to the name of the active document. This error is not caught during design time because it is not a syntax error. It is only at compile time, when Word considers the statement in the context of the first statement, that the error becomes evident.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Debugging
Invariably, you will encounter errors in your code. Design-time and compile-time errors are relatively easy to deal with because Word helps us out with error messages and by indicating the offending code. Logical errors are much more difficult to detect and to fix. This is where debugging plays a major role. The Word IDE provides some very powerful ways to find bugs.
Debugging can be quite involved, and I could include a whole chapter on the subject. There are even special software applications designed to assist in complex debugging tasks. However, for most purposes, a few simple techniques are sufficient. In particular, Word makes it easy to trace through programs, executing one line at a time, watching the effect of each line as it is executed.
Try a very simple example, with which you should follow along on your PC. If possible, you should arrange your screen as in . This will make it easier to follow the effects of the code, since you won't need to switch back and forth between the Word window and the Word VBA window. The code that we will trace is shown in . (Note that lines beginning with an apostrophe are comments that are ignored by Word.)
Example . A Simple Program to Trace
Sub test()

Dim sent As Range
' Get the third sentence
Set sent = ActiveDocument.Range.Sentences(3)
' Select it
sent.Select
' Boldface it
sent.Bold = True
' Select the first character in the sentence
sent.Characters(1).Select
' Change the font
Selection.Font.Size = 24

End Sub
Begin by entering a paragraph containing at least three sentences into a Word document and leave the cursor anywhere in the document. When you finish, switch to the VBA IDE. Make sure that the code window is active and the insertion point is somewhere in the code. Then hit the F8 key once, which starts the tracing process. (You can also choose Step Into from the Debug menu.)
Continue striking the F8 key, pausing between keystrokes to view the effect of each instruction in the Word window. (You can toggle between Word and the IDE using Alt-F11.) As you trace through this code, you will see the third sentence selected, made bold, the first character selected, and finally its font size increased. Now you can begin to see what Word VBA programming is all about!
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Macros
In earlier days, a macro consisted of a series of keystrokes that was recorded and assigned to a hotkey. When a user invoked the hotkey, the recording would play and the recorded keystrokes would be executed.
These days, macros (at least for Microsoft Office) are much more sophisticated. In fact, a Word macro is just a special type of subroutine—one that does not have any parameters. (I discuss subroutines and parameters in , Functions and Subroutines.)
Word has the capability of recording very simple macros. When we ask Word to record a macro, it takes note of our keystrokes and converts them into a VBA subroutine (with no parameters).
For example, suppose you record a macro that does a find and replace, replacing the word "macro" with the word "subroutine." When you look in the Projects window under the project in which the macro was recorded (usually the attached template), you will find a new standard module called NewMacros containing the following subroutine:
	Sub AMacro()
	'
	AMacro Macro
	Macro recorded 04/27/98 by sr
	'
	   Selection.Find.ClearFormatting
	   Selection.Find.Replacement.ClearFormatting
	   With Selection.Find
	      .Text = "macro"
	      .Replacement.Text = "subroutine"
	      .Forward = True
	      .Wrap = wdFindContinue
	      .Format = False
	      .MatchCase = False
	      .MatchWholeWord = False
	      .MatchWildcards = False
	      .MatchSoundsLike = False
	      .MatchAllWordForms = False
	   End With
	   Selection.Find.Execute
	   Selection.Find.Execute Replace:=wdReplaceAll
	End Sub
This is the same code that someone might have written in order to perform this find and replace operation.
Word does a very thorough job of translating keystrokes into VBA code, essentially matching in code every item in the Find and Replace dialog box shown in —even the ones that we have not changed—because it has no way of knowing what we have and have not changed!
Figure : The Find and Replace dialog box
In certain situations, the macro recorder can serve as a useful learning tool. If we can't figure out how to code a certain action, we can record it in a macro and cut and paste the resulting code into our own program.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 5: Variables, Data Types, and Constants
In this chapter:
  • Comments
  • Line Continuation
  • Constants
  • Variables and Data Types
  • VBA Operators
In the next few chapters, I discuss the basics of the VBA programming language, which underlies all of the Microsoft Office programming environments. During the discussion, I provide many short coding examples. I hope that you will take the time to enter some of these examples and experiment with them.
We have already examined the importance of comments. Any text that follows an apostrophe is considered a comment and is ignored by Word. For example, the first following line is a comment, as is everything following the apostrophe on the third line:
' Declare a string variable
	Dim DocName as String
	DocName = ActiveDocument.Name   ' Get name of active doc
One of the more useful tools when debugging code is to temporarily comment out lines of code so that they will not execute. The lines can subsequently be uncommented to restore them to active duty. The CommentBlock and UncommentBlock buttons, which can be found on the Edit toolbar, will place or remove comment marks from each currently selected line of code and are very useful for commenting out several lines of code in one step. (There are no keyboard shortcuts for these commands, but they can be added to a menu and given menu accelerator keys.)
The very nature of Word VBA syntax often leads to long lines of code, which can be difficult to read, especially if we need to scroll horizontally to see the entire line. For this reason, Microsoft recently introduced a line-continuation character into VBA. This character is the underscore (_), which must be preceded by a space and cannot be followed by any other characters (including comments). For example, the following code:
	ActiveDocument.Paragraphs(1).Alignment = _
	wdAlignParagraphCenter
is treated as one line by Word.
A line-continuation character cannot be inserted in the middle of a literal string constant, which is enclosed in quotation marks.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Comments
We have already examined the importance of comments. Any text that follows an apostrophe is considered a comment and is ignored by Word. For example, the first following line is a comment, as is everything following the apostrophe on the third line:
' Declare a string variable
	Dim DocName as String
	DocName = ActiveDocument.Name   ' Get name of active doc
One of the more useful tools when debugging code is to temporarily comment out lines of code so that they will not execute. The lines can subsequently be uncommented to restore them to active duty. The CommentBlock and UncommentBlock buttons, which can be found on the Edit toolbar, will place or remove comment marks from each currently selected line of code and are very useful for commenting out several lines of code in one step. (There are no keyboard shortcuts for these commands, but they can be added to a menu and given menu accelerator keys.)
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Line Continuation
The very nature of Word VBA syntax often leads to long lines of code, which can be difficult to read, especially if we need to scroll horizontally to see the entire line. For this reason, Microsoft recently introduced a line-continuation character into VBA. This character is the underscore (_), which must be preceded by a space and cannot be followed by any other characters (including comments). For example, the following code:
	ActiveDocument.Paragraphs(1).Alignment = _
	wdAlignParagraphCenter
is treated as one line by Word.
A line-continuation character cannot be inserted in the middle of a literal string constant, which is enclosed in quotation marks.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Constants
The VBA language has two types of constants. A literal constant (also called a constant or literal) is a specific value, such as a number, date, or text string, that does not change and that is used exactly as written. Note that string constants are enclosed in double quotation marks, as in:
	"Donna Smith"
and date constants are enclosed between number signs, as in:
	#1/1/96#
For instance, the following code stores a date in the variable called dt:
	Dim dt As Date
	dt = #1/2/97#
The second type of constant, a symbolic constant (also sometimes referred to simply as a constant), is another name for a literal constant.
To define or declare a symbolic constant in a program, use the Const keyword:
	Const InvoicePath = "d:\Invoices\"
In this case, Word will replace every instance of InvoicePath in our code with the string "d:\Invoices\". Thus, InvoicePath is a constant, since it never changes value, but it is not a literal constant, since it is not used as written.
The virtue of using symbolic constants is that, if we decide later to change "d:\ Invoices\" to "d:\OldInvoices\", you need to change only the definition of InvoicePath:
	Const InvoicePath = "d:\OldInvoices\"
rather than search through the entire program for every occurrence of the phrase "d:\Invoices\"!
Note that it is generally good programming practice to declare any symbolic constants at the beginning of the procedure in which they are used (or in the Declarations section of a code module). This improves readability and simplifies housekeeping.
In addition to the symbolic constants that you can define using the Const statement, VBA has a large number of built-in symbolic constants (about 700), whose names begin with the lowercase letters vb. Word VBA adds additional symbolic constants (about 2,000!) that begin with the letters wd. You will encounter many of these constants throughout the book.
Among the most commonly used VBA constants are vbCrLf, which is equivalent to a carriage return followed by a line feed, and vbTab, which is equivalent to the tab character. Also, Word uses vbCr for its paragraph mark.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Variables and Data Types
A variable can be thought of as a memory location that can hold values of a specific type. The value in a variable may change during the life of the program—hence the name "variable."
In VBA, each variable has a specific data type, which indicates which type of data it may hold. For instance, a variable that holds text strings has the data type String and is called a string variable. A variable that holds integers (whole numbers) has the data type Integer and is called an integer variable. For reference, shows the complete set of VBA data types, along with the amount of memory that they consume and their range of values. (I will discuss a few of the more commonly used data types in a moment.)
Table : VBA Data Types
Type
Size in Memory
Range of Values
Byte
1 byte
0 to 255
Boolean
2 bytes
True or False
Integer
2 bytes
–32,768 to 32,767
Long (long integer)
4 bytes
–2,147,483,648 to 2,147,483,647
Single (single-precision real)
4 bytes
Approximately –3.4E38 to 3.4E38
Double (double-precision real)
8 bytes
Approximately –1.8E308 to 4.9E324
Currency (scaled integer)
8 bytes
Approximately –922,337,203,685,477.5808 to 922,337,203,685,477.5807
Date
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
VBA Operators
Content preview·Buy PDF of this chapter