You are on page 1of 12

11/04/2021 Debugging - Writing Word Macros, Second Edition [Book]

See everything available through O’Reilly online Search

Writing Word Macros, Second Edition by Steven Roman…

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 of-
fending 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 applica-
tions 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, ex-
ecuting one line at a time, watching the effect of each line as it
is executed.

https://www.oreilly.com/library/view/writing-word-macros/9781565927254/ch04s06.html 1/12
11/04/2021 Debugging - Writing Word Macros, Second Edition [Book]

Try a very simple example, with which you should follow along
on your PC. If possible, you should arrange your screen as in
Figure 4-10. 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 Example 4-1. (Note that lines beginning
with an apostrophe are comments that are ignored by Word.)

Example 4-1. 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 sen-


tences 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

https://www.oreilly.com/library/view/writing-word-macros/9781565927254/ch04s06.html 2/12
11/04/2021 Debugging - Writing Word Macros, Second Edition [Book]

the tracing process. (You can also choose Step Into from the De-
bug 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 selec-
ted, made bold, the first character selected, and finally its font
size increased. Now you can begin to see what Word VBA pro-
gramming is all about!

Figure 4-10. Side-by-side windows for easy debugging

I will now examine some of the tools that Word provides for de-
bugging code.

https://www.oreilly.com/library/view/writing-word-macros/9781565927254/ch04s06.html 3/12
11/04/2021 Debugging - Writing Word Macros, Second Edition [Book]

Tracing
The process of executing code one line at a time, as I did in the
previous example, is referred to as tracing or code stepping. Word
provides three options related to tracing: stepping into, step-
ping over, and stepping out of. The differences between these
methods refers to handling calls to other procedures.

To illustrate the difference, consider the code shown in


Example 4-2. In ProcedureA, the first line of code sets the con-
tents of the active Word document to the line “To be or not to
be.” The second line calls ProcedureB and the third line boldfaces
the contents of the active document. ProcedureB simply formats
the first paragraph of the active Word document with the Head-
ing 1 style. Don’t worry about the exact syntax of this code. The
important thing to notice is that the second line of ProcedureA
calls ProcedureB.

Example 4-2. Sample Code for Tracing Methods

Sub ProcedureA()
ActiveDocument.Content.Text = "To be or not to be"
Call ProcedureB
ActiveDocument.Content.Bold = True
End Sub

Sub ProcedureB()
Set para = ActiveDocument.Paragraphs(1)
para.Style = "Heading 1"
End Sub

https://www.oreilly.com/library/view/writing-word-macros/9781565927254/ch04s06.html 4/12
11/04/2021 Debugging - Writing Word Macros, Second Edition [Book]

Step Into (F8)


Step Into executes code one statement (or instruction) at a time.
If the statement being executed calls another procedure, step-
ping into that statement simply transfers control to the first line
in the called procedure. For instance, with reference to the pre-
vious code, stepping into the line:

Call ProcedureB

in ProcedureA transfers control to the first line of ProcedureB:

Set para = ActiveDocument.Paragraphs(1)

Further tracing proceeds in ProcedureB. Once all of the lines of


ProcedureB have been traced, control returns to ProcedureA at
the line immediately following the call to ProcedureB, that is, at
the line:

ActiveDocument.Content.Bold = True

Step Into has another important use. Namely, if we choose Step


Into while still in design mode—that is, before any code is run-
ning—execution begins but break mode is entered before the first
line of code is actually executed. This is the proper way to begin
tracing a program.

Step Over (Shift-F8)

https://www.oreilly.com/library/view/writing-word-macros/9781565927254/ch04s06.html 5/12
11/04/2021 Debugging - Writing Word Macros, Second Edition [Book]

Step Over is similar to Step Into, except that if the current state-
ment is a call to another procedure, the entire called procedure
is executed without stopping (rather than tracing through the
called procedure). Thus, for instance, stepping over the line:

Call ProcedureB

in the previous procedure executes ProcedureB and stops at the


next line:

ActiveDocument.Content.Bold = True

in ProcedureA. This is useful if we are certain that ProcedureB is


not the cause of our problem and we don’t want to trace
through that procedure line by line.

Step Out (Ctrl-Shift-F8)


Step Out is intended to be used within a called procedure (such
as ProcedureB). Step Out executes the remaining lines of the
called procedure and returns to the calling procedure (such as
ProcedureA). This is useful if we are in the middle of a called pro-
cedure and decide that we don’t need to trace any more of that
procedure, but want to return to the calling procedure. (If you
trace into a called procedure by mistake, just do a Step Out to
return to the calling procedure.)

Run To Cursor

https://www.oreilly.com/library/view/writing-word-macros/9781565927254/ch04s06.html 6/12
11/04/2021 Debugging - Writing Word Macros, Second Edition [Book]

If the Visual Basic Editor is in break mode, we may want to ex-


ecute several lines of code at one time. This can be done using
the Run To Cursor feature. Simply place the cursor on the state-
ment immediately following the last line you want to execute and
then press Ctrl-F8 (or choose Run To Cursor from the Debug
menu).

Changing the next statement to execute

We can also change the flow of execution while in break mode


by placing the cursor on the statement that we want to execute
next and hitting Ctrl-F9 or choosing Set Next Statement from
the Debug menu. This will set the selected statement as the
next statement to execute (but will not execute it until we con-
tinue tracing). What power!

Breaking out of debug mode

When we no longer need to trace our code, we have two


choices. To return to design mode, we can choose Reset from
the Run menu (no hotkey for this). To have Word finish execut-
ing the current program, we can hit F5 or choose Run from the
Run menu.

Watching Expressions
It is often useful to watch the values of certain expressions or
variables as we trace through a program. Word provides several
ways to do this.

https://www.oreilly.com/library/view/writing-word-macros/9781565927254/ch04s06.html 7/12
11/04/2021 Debugging - Writing Word Macros, Second Edition [Book]

Quick Watch (Shift-F9)

The Quick Watch feature is used to check the value of a variable


or expression quickly while in break mode. Just place the inser-
tion point over the variable name and hit Shift-F9 (or choose
Quick Watch from the Debug menu). For instance, Figure 4-11
shows the Quick Watch dialog box when the expression x + 2
is selected in the code in Figure 4-12. According to Figure 4-11,
at the time that Quick Watch was invoked, the expression x +
2 had the value 8. Note that if I had just placed the insertion
point in front of the letter x, then Quick Watch would have re-
ported the value of this variable alone.

Figure 4-11. The Quick Watch window

Another way to get values for expressions or variables quickly is


to enable Auto Data Tips on the Editor tab of in Word VBA’s Op-
tions dialog box. With this feature enabled, when we place the
mouse pointer over a variable or select an expression and place
the mouse pointer over the selection, after a slight delay, a
small yellow window will appear containing the value of the
variable or expresion. This is very useful!

The Locals and Watch Window

https://www.oreilly.com/library/view/writing-word-macros/9781565927254/ch04s06.html 8/12
11/04/2021 Debugging - Writing Word Macros, Second Edition [Book]

Two special windows aid in watching expressions: the Locals


window and the Watch window. These are shown in Figure 4-12.

Figure 4-12. The Locals and Watch windows

The Locals window shows the values of all local variables. A


local variable is a variable defined within the current procedure
and is therefore not valid in any other procedure. (I discuss local
variables in Chapter 5, Variables, Data Types, and Constants.)

The Watch window shows all of the watches that have been set.
A watch is a variable or expression that is placed in the Watch
window. Word automatically updates the expressions in the
Watch window after each line of code is executed and acts ac-
cording to the type of watch defined, as described next.

To add a watch, choose Add Watch from the Debug menu. This
will produce the dialog box shown in Figure 4-13.

https://www.oreilly.com/library/view/writing-word-macros/9781565927254/ch04s06.html 9/12
11/04/2021 Debugging - Writing Word Macros, Second Edition [Book]

Figure 4-13. The Add Watch dialog box

You can then enter a variable or expression, such as x > 6, in


the Expression text box. Note that there are three types of
watches:

Watch Expression simply adds the expression to the


Watches window so you can watch its value as code is ex-
ecuted. In this example, the value of the expression will be
either True or False, depending upon whether x > 6 or
not.

Break When Value Is True asks Word to stop execution and


enter break mode whenever the expression is true. In this
example, VBA will break execution when x > 6 is true,
that is, when x becomes greater than 6.

Break When Value Changes asks Word to enter break mode


when the value of the expression changes in any way (in
this case, from True to False or vice-versa).

https://www.oreilly.com/library/view/writing-word-macros/9781565927254/ch04s06.html 10/12
11/04/2021 Debugging - Writing Word Macros, Second Edition [Book]

Altogether, the various tracing modes and watch types provide


a very powerful set of tools for debugging code. I use them of-
ten!

Get Writing Word Macros, Second Edition now with


O’Reilly online learning.

O’Reilly members experience live online training, plus


books, videos, and digital content from
200+ publishers.

START YOUR FREE TRIAL

ABOUT O’REILLY

Teach/write/train

Careers
Community partners

Affiliate program

Submit an RFP
Diversity

O’Reilly for marketers

https://www.oreilly.com/library/view/writing-word-macros/9781565927254/ch04s06.html 11/12
11/04/2021 Debugging - Writing Word Macros, Second Edition [Book]

SUPPORT
Contact us

Newsletters

Privacy policy

DOWNLOAD THE O’REILLY APP

Take O’Reilly online learning with you and learn anywhere, anytime on your phone
and tablet.

WATCH ON YOUR BIG SCREEN

View all O’Reilly videos, Superstream events, and Meet the Expert sessions on your
home TV.

DO NOT SELL MY PERSONAL INFORMATION


Exercise your consumer rights by contacting us at donotsell@oreilly.com.

© 2021, O’Reilly Media, Inc. All trademarks and registered trademarks appearing on oreilly.com are the
property of their respective owners.
Terms of service • Privacy policy • Editorial independence

https://www.oreilly.com/library/view/writing-word-macros/9781565927254/ch04s06.html 12/12

You might also like