Chapter 7. Macro Hacks
Introduction: Hacks #57-69
When it comes to hacking Word, VBA macros are often the answer. From automating routine tasks to redefining Word’s behavior, macros are a potent weapon in your Word arsenal. The hacks in this chapter show several ways to move beyond basic automation, as well as how to make your macros faster, friendlier, and more flexible.
Get Simple User Input for a Macro
Macros that interact with the user can be very useful. This hack shows you how to get feedback from a user without the overhead or complexity of a VBA UserForm.
When you get input from
a user (often yourself), you may want
to present the person with several choices. You can use a
UserForm
with radio buttons or checkboxes, but it
might add unnecessary overhead and complexity. Instead, use the
dialogs already built into VBA, such as the MsgBox
and InputBox
.
For example, if you just need the user to select between two
choices—say, “Red” or
“Blue”—you could display a
standard MsgBox
with its included
“Yes” and
“No” buttons. The following macro
displays the dialog shown in Figure 7-1:
Sub PickRedOrBluePlease( ) Dim lResponse As Long lResponse = MsgBox(Prompt:="Press Yes for Red, Press No for Blue", _ Buttons:=vbYesNo, _ Title:="Pick a color") If lResponse = vbYes Then MsgBox "You picked Red" Else MsgBox "You picked Blue" End If End Sub
Get Word Hacks 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.