With this method, you start the macro recording feature and then run through the operations you want to auto-mate—which can include selecting text, running commands from the Ribbon the O
Trang 2C o n t e n t s a t a G l a n c e
I Getting Started with VBA
1 Creating and Running Recorded Macros 3
2 Writing Your Own Macros 15
3 Understanding Program Variables 33
4 Building VBA Expressions 53
5 Working with Objects 71
6 Controlling Your VBA Code 91
II Putting VBA to Work 7 Programming Word 115
8 Programming Excel 139
9 Programming PowerPoint 165
10 Programming Access Databases 189
11 Programming Outlook Email 213
III Getting the Most Out of VBA 12 Creating Custom VBA Dialog Boxes 237
13 Customizing the Office 2007 Ribbon 263
14 VBA Tips and Techniques 299
15 Trapping Program Errors 323
16 Debugging VBA Procedures 337
IV Appendixes A VBA Statements 355
B VBA Functions 361
Index 371
Paul McFedries
800 E 96th Street
Indianapolis, Indiana 46240
VBA
for the
Office System
?
Trang 3All rights reserved No part of this book shall be reproduced, stored in a retrieval system,
or transmitted by any means, electronic, mechanical, photocopying, recording, or otherwise,
without written permission from the publisher No patent liability is assumed with respect
to the use of the information contained herein Although every precaution has been taken in
the preparation of this book, the publisher and author assume no responsibility for errors
or omissions Nor is any liability assumed for damages resulting from the use of the
information contained herein.
International Standard Book Number: 0-7897-3667-5
Library of Congress Cataloging-in-Publication Data
McFedries, Paul.
VBA for the 2007 Microsoft Office system / Paul McFedries.
p cm.
ISBN 0-7897-3667-5
1 Microsoft Office 2 Microsoft Visual Basic for applications 3 Business—
Computer programs 4 Integrated software I Title
HF5548.4.M525M395 2007
005.5—dc22
2007004121 Printed in the United States of America
First Printing: April 2007
Trademarks
All terms mentioned in this book that are known to be trademarks or service marks have
been appropriately capitalized Que Publishing cannot attest to the accuracy of this
infor-mation Use of a term in this book should not be regarded as affecting the validity of any
trademark or service mark.
Warning and Disclaimer
Every effort has been made to make this book as complete and as accurate as possible,
but no warranty or fitness is implied The information provided is on an “as is” basis.
The author and the publisher shall have neither liability nor responsibility to any person
or entity with respect to any loss or damages arising from the information contained in
this book.
Bulk Sales
Que Publishing offers excellent discounts on this book when ordered in quantity for
bulk purchases or special sales For more information, please contact
U.S Corporate and Government Sales
Trang 4Introduction xvii
What Is a Macro? xviii
What Does VBA Have to Do with Macros? xix
What You Should Know Before Reading This Book xix
What’s in the Book xx
This Book’s Special Features xx
I GETTING STARTED WITH VBA 1 Creating and Running Recorded Macros 3
Recording a VBA Macro 5
Recording a Word Macro 5
Recording an Excel Macro 7
Running a Recorded Macro 8
Using the Macro Name List 8
Assigning Shortcut Keys to Recorded Word Macros 9
Assigning Shortcut Keys to Recorded Excel Macros 10
Creating a Quick Access Toolbar Button for a Recorded Macro 11
From Here 13
2 Writing Your Own Macros 15
Activating the Ribbon’s Developer Tab 16
Displaying the Visual Basic Editor 16
Touring the Visual Basic Editor 17
Creating a New Module 17
Opening an Existing Module 18
Understanding VBA Procedures 19
Creating a Command Macro 19
Writing a Command Macro 20
Running a Command Macro 21
Entering VBA Statements 22
Creating a User-Defined Function 23
Understanding User-Defined Functions 24
Writing a User-Defined Function 25
Using a Function 26
Taking Advantage of IntelliSense 27
List Properties/Methods 27
Trang 5Parameter Info 29
Complete Word 30
Shutting Down the Visual Basic Editor 30
From Here 30
3 Understanding Program Variables 33
Declaring Variables 33
Avoiding Variable Errors 35
Variable Data Types 36
Changing the Default Data Type 39
Creating User-Defined Data Types 39
Using Array Variables 40
Dynamic Arrays 41
Multidimensional Arrays 44
Working with Constants 44
Using Built-In Constants 44
Creating User-Defined Constants 45
Storing User Input in a Variable 45
Getting Input Using MsgBox 45
Getting Input Using InputBox 50
From Here 51
4 Building VBA Expressions 53
Understanding Expressions 53
Working with VBA Operators 54
Arithmetic Operators 55
The Concatenation Operator 56
Comparison Operators 56
Logical Operators 57
Understanding Operator Precedence 57
The Order of Precedence 58
Controlling the Order of Precedence 58
Working with Numeric Expressions 60
VBA’s Math Functions 60
VBA’s Financial Functions 62
Working with String Expressions 63
Working with Logical Expressions 66
TheAndOperator 67
TheOrOperator 67
TheXorOperator 67
TheNotOperator 67
Working with Date Expressions 68
Trang 65 Working with Objects 71
What Is an Object? 71
The Object Hierarchy 73
Working with Object Properties 73
Setting the Value of a Property 75
Returning the Value of a Property 75
Working with Object Methods 75
Handling Object Events 77
Working with Object Collections 78
Assigning an Object to a Variable 79
TheIsOperator 80
Working with Multiple Properties or Methods 80
Example: The ApplicationObject 81
Displaying a Message in the Status Bar 82
Changing the Title Bar Caption 82
Working with the Application Window 82
Accessing an Application’s Built-In Dialog Boxes 83
Checking Spelling 87
Example: The WindowObject 88
Specifying a WindowObject 88
Opening a New Window 88
Activating a Window 88
From Here 89
6 Controlling Your VBA Code 91
Code That Makes Decisions 91
UsingIf Thento Make True/False Decisions 92
UsingIf Then Elseto Handle a False Result 93
Making Multiple Decisions 94
Using the AndandOrOperators 95
Using Multiple If Then ElseStatements 95
Using the Select CaseStatement 97
Functions That Make Decisions 101
TheIIfFunction 101
TheChooseFunction 102
TheSwitchFunction 103
Code That Loops 104
UsingDo LoopStructures 105
UsingFor NextLoops 106
UsingFor Each NextLoops 109
v
Contents
Trang 7UsingExitFor or Exit Doto Exit a Loop 110
Indenting for Readability 111
From Here 111
II PUTTING VBA TO WORK 7 Programming Word 115
Working with Documents 115
Specifying a DocumentObject 115
Opening a Document 116
TheRecentFilesObject 116
Creating a New Document 118
Saving a Document 118
Closing a Document 121
Closing All Open Documents 121
Example: Making Document Backups 122
Working with Text 124
Working with the RangeObject 125
TheRangeMethod 125
TheRangeProperty 125
Reading and Changing Range Text 126
Formatting Text 126
Inserting Text 127
Deleting Text 128
Using the SelectionObject 129
Checking the SelectionType 129
Moving the Insertion Point 130
Extending the Selection 131
Collapsing the Selection 132
Using the WordsObject 132
Working with the SentencesObject 133
Displaying Sentence Word Counts 134
Programming the ParagraphObject 136
From Here 138
8 Programming Excel 139
Excel’s Application Object 139
Accessing Worksheet Functions 139
Recalculating Workbooks 140
Converting a String into an Object 140
Pausing a Running Macro 141
Trang 8ManipulatingWorkbookObjects 146
Specifying a WorkbookObject 146
Opening a Workbook 146
Creating a New Workbook 147
Specifying the Number of Sheets in a New Workbook 147
Saving Every Open Workbook 148
Closing a Workbook 150
Dealing with WorksheetObjects 150
Specifying a WorksheetObject 150
Creating a New Worksheet 151
Properties of the WorksheetObject 151
Methods of the WorksheetObject 152
Working with RangeObjects 153
Returning a RangeObject 153
Selecting a Cell or Range 158
Defining a Range Name 162
Inserting Data into a Range 162
Returning Data About a Range 163
Resizing a Range 163
From Here 164
9 Programming PowerPoint 165
PowerPoint’s PresentationObject 165
Specifying a PresentationObject 165
Opening a Presentation 166
Creating a New Presentation 166
PresentationObject Properties 166
PresentationObject Methods 167
The Juggling Application 168
Working with PowerPoint Slide Objects 170
Specifying a Slide 170
Creating a New Slide 171
Inserting Slides from a File 172
SlideObject Properties 172
The Juggling Application: Creating the Slides 173
SlideObject Methods 174
Dealing with ShapeObjects 174
Specifying a Shape 174
Adding Shapes to a Slide 175
SomeShapeObject Properties 178
The Juggling Application: Creating the Title Slide 180
SomeShapeObject Methods 181
vii
Contents
Trang 9Operating a Slide Show 186
Slide Show Transitions 186
Slide Show Settings 187
Running the Slide Show 187
From Here 188
10 Programming Access Databases 189
Getting Ready: Two Steps Before You Begin 190
Step One: Create a Reference 190
Step Two: Create a Data Source 191
Working with Database Records: Opening a Recordset 192
Opening a Recordset Using a Table 193
Opening a Recordset: the Full OpenMethod Syntax 194
Opening a Recordset Using a SELECTString 196
Working with a Recordset 198
Getting at the Recordset Data 198
Navigating Records 199
Finding a Record 202
Editing a Record 203
Adding a New Record 205
Deleting a Record 207
Retrieving Data into Excel 208
Retrieving an Individual Field Value 208
Retrieving One or More Entire Rows 208
Retrieving an Entire Recordset 210
From Here 212
11 Programming Outlook Email 213
Getting Started 213
Working with Outlook Folders 214
Referencing Default Folders 214
Using the FoldersProperty 214
Prompting the User for a Folder 216
SomeMAPIFolderMethods 217
Handling Incoming and Outgoing Messages 217
Incoming: Handling the ItemAddEvent 218
Outgoing: Handling the ItemSendEvent 219
Working with Email Messages 220
MailItemObject Properties 220
MailItemObject Methods 221
Example: Creating Advanced Rules for Incoming Messages 223
Example: Canning Spam 224
Sending a Message 225
Creating a New Message 225
Trang 10Specifying the Message Recipients 226
Sending the Message 226
Example: Supplementing a Reminder with an Email Message 227
Working with Attachments 229
Example: Removing Attachments from a Forwarded Message 229
Attaching a File to a Message 230
Programming Outlook from Other Applications 231
Setting Up a Reference to Outlook 231
Getting the NameSpaceObject 232
Logging On to an Outlook Session 232
Logging Off an Outlook Session 233
From Here 234
III GETTING THE MOST OUT OF VBA 12 Creating Custom VBA Dialog Boxes 237
Adding a Form to Your Project 238
Changing the Form’s Design-Time Properties 239
The Appearance Category 239
The Behavior Category 239
The Font Category 240
The Misc Category 240
The Picture Category 241
The Position Category 241
The Scrolling Category 241
Working with Controls 242
Inserting Controls on a Form 242
Selecting Controls 243
Sizing Controls 244
Moving Controls 244
Copying Controls 244
Deleting Controls 245
Grouping Controls 245
Setting Control Properties 246
Common Control Properties 246
Setting the Tab Order 247
Handling Form Events 248
Types of Form Controls 248
Command Buttons 249
Labels 249
Text Boxes 249
Frames 250
ix
Contents
Trang 11Check Boxes 251
Toggle Buttons 251
List Boxes 251
Scrollbars 253
Spin Buttons 253
Tab Strips and MultiPage Controls 254
Using a Form in a Procedure 258
Displaying the Form 258
Unloading the Form 258
Processing the Form Results 259
From Here 262
13 Customizing the Office 2007 Ribbon 263
Understanding Ribbon Extensibility 263
Extending the Ribbon: An Example 265
Step 1: Create a Macro-Enabled Office Document or Template 265
Step 2: Create a Text File and Add the Custom XML Markup 267
Step 3: Copy the Custom XML Markup File to the Document Package 268
Step 4: Rename and Open the Document 269
More Complexity Means More Power 270
Hiding the Built-In Ribbon 270
Creating Custom Tabs 271
Creating a New Tab 271
Customizing an Existing Tab 272
Creating Custom Groups 273
Creating a New Group 274
Customizing an Existing Group 274
Creating Custom Controls 275
Common Control Attributes 276
Creating a Button 277
Creating a Menu 278
Creating a Split Button 280
Creating a Check Box 281
Creating a Toggle Button 282
Creating a Drop-Down List 284
Creating a Gallery 285
Creating a Combo Box 288
Creating a Dialog Launcher 289
Working with Ribbon Commands at Runtime 289
From Here 297
14 VBA Tips and Techniques 299
Working with Modules 299
Renaming a Module 299
Trang 12Importing a Module 300
Removing a Module 301
Configuring Macro Security Settings 301
Setting Up a Trusted Location 301
Setting the Macro Security Level 302
Digitally Signing a VBA Project 304
Saving Application Settings in the Registry 305
Storing Settings in the Registry 306
Reading Settings from the Registry 306
Deleting Settings from the Registry 307
Tracking File Usage 307
Reading All the Section Settings 309
Accessing the File System Through VBA 309
Returning File and Folder Information 310
Manipulating Files and Folders 314
Tips for Faster Procedures 319
Turn Off Screen Updating 319
Hide Your Documents 319
Don’t Select Data Unless You Have To 319
In Excel, Don’t Recalculate Until You Have To 319
Optimize Your Loops 320
From Here 321
15 Trapping Program Errors 323
A Basic Error-Trapping Strategy 324
Setting the Trap 324
Coding the Error Handler 325
Resuming Program Execution 327
Disabling the Trap 330
Working with the ErrObject 330
ErrObject Properties 330
ErrObject Methods 332
Trappable VBA Errors 333
From Here 336
16 Debugging VBA Procedures 337
A Basic Strategy for Debugging 338
Syntax Errors 338
Compile Errors 338
Runtime Errors 338
Logic Errors 339
Pausing a Procedure 339
Entering Break Mode 340
Exiting Break Mode 342
xi
Contents
Trang 13Stepping Through a Procedure 342
Stepping into a Procedure 343
Stepping Over a Procedure 343
Stepping Out of a Procedure 343
Stepping to the Cursor 343
Monitoring Procedure Values 344
Using the Locals Window 344
Adding a Watch Expression 344
Editing a Watch Expression 346
Deleting a Watch Expression 346
Displaying Data Values Quickly 347
Using the Immediate Window 348
Printing Data in the Immediate Window 348
Executing Statements in the Immediate Window 350
Debugging Tips 350
Indent Your Code for Readability 350
Turn on Syntax Checking 351
Require Variable Declarations 351
Break Down Complex Procedures 351
Enter VBA Keywords in Lowercase 351
Comment Out Problem Statements 351
Break Up Long Statements 351
Use Excel’s Range Names Whenever Possible 352
Take Advantage of User-Defined Constants 352
From Here 352
IV APPENDIXES A VBA Statements 355
B VBA Functions 361
Index 371
Trang 14About the Author
Paul McFedries is well-known as a teacher of Office, Windows, and programming,
partic-ularly VBA He is the president of Logophilia Limited, a technical writing company Paulstarted programming when he was a teenager in the mid-1970s and has worked with every-thing from mainframes to desktops to bar code scanners He has programmed in many dif-ferent languages, including Fortran, assembly language, C++, Java, JavaScript, Visual Basic,and VBScript He has been writing programs for PCs for more than 25 years, and has beendeveloping VBA applications since Microsoft first added VBA to the Office suite in 1994.Now primarily a writer, Paul has written more than 50 books that have sold more than
three million copies worldwide These books include Access 2007 Forms, Reports, and Queries (Que, 2007), Formulas and Functions with Excel 2007 (Que, 2007), Tricks of the Office 2007
Gurus (Que, 2007), and Windows Vista Unleashed (Sams, 2006).
Trang 15To Karen and Gypsy.
Acknowledgments
Robert Pirsig, in Zen and the Art of Motorcycle Maintenance, wrote that “a person who sees
Quality and feels it as he works, is a person who cares.” If this book is a quality product(and I immodestly think that it is), it’s because the people at Que editorial cared enough tomake it so
So a round of hearty thanks is in order for all the good people who worked on this project.You’ll find them all listed near the front of the book, but I’d like to extend special kudos tothe folks I worked with directly: Acquisitions Editor Loretta Yates, Development EditorTodd Brakke, Production Editor Betsy Harris, Copy Editor Margo Catts, and Tech EditorGreg Perry
Trang 16We Want to Hear from You!
As the reader of this book, you are our most important critic and commentator We valueyour opinion and want to know what we’re doing right, what we could do better, what areasyou’d like to see us publish in, and any other words of wisdom you’re willing to pass ourway
As an associate publisher for Que Publishing, I welcome your comments You can email orwrite me directly to let me know what you did or didn’t like about this book—as well aswhat we can do to make our books better
Please note that I cannot help you with technical problems related to the topic of this book We do have a User Services group, however, where I will forward specific technical questions related to the book.
When you write, please be sure to include this book’s title and author as well as your name,email address, and phone number I will carefully review your comments and share themwith the author and editors who worked on the book
Associate Publisher Que Publishing
800 East 96th StreetIndianapolis, IN 46240 USA
Reader Services
Visit our website and register this book at www.quepublishing.com/register for convenientaccess to any updates, downloads, or errata that might be available for this book
Trang 18I N T H I S I N T R O D U C T I O N
Introduction
What Is a Macro? xviii What Does VBA Have to Do with Macros? xix What You Should Know Before Reading This Book xix What’s in the Book xx This Book’s Special Features xx
Visual Basic for Applications is a mouthful to say
(which is why I’ll use the standard short form—
VBA—from now on), but it also seems like it would
be a real handful to learn After all, this is a
pro-gramming language we’re talking about, right?
True, but VBA was designed to be easy to learn and
straightforward to apply I’ve learned a couple of
dozen programming languages over the past 30
years or so, and I can tell you that VBA is, hands
down, the easiest language I’ve ever worked with
Okay, but isn’t this stuff just for power users and the
staff of the Information Technology department?
Yes, VBA is a useful tool for hardcore users and
those who need to design major projects But VBA
can be immensely useful for every user As a writer,
I use Word constantly, and over the years I’ve
developed dozens of small macros, functions, and
forms that streamline or automate repetitive chores
Most of these routines consist of only a few lines of
code, and each one saves me only about 30 seconds
to a minute, depending on the task But I use these
routines 50 or 100 times a day, so I end up saving
myself anywhere from 30 to 90 minutes a day!
That’s pretty remarkable, but the proof is in the
pudding: I can now write far more pages in a day
than I used to (Don’t tell my editor!)
Whether your concern is ease-of-use or personal
productivity, there’s little doubt VBA can make
working with the Office applications a better
expe-rience So now all you have to do is learn how to
use it, and that’s where this book comes in My goal
in writing this book was to give you an introduction
to the VBA language, and to give you plenty of
examples for putting the language to good use
Even if you’ve never even programmed your VCR,
this book will teach you VBA programming from
the ground up The first six chapters, in particular,
give you all the know-how you’ll need to be a
com-petent and productive programmer
I N T R O D U C T I O N
Trang 19What Is a Macro?
It doesn’t matter in which Office program you’re working—it could be Word, it could beExcel, it could be PowerPoint A few times a day you probably find yourself performingsome chore that either you’ve done dozens of times in the past, or that you have to repeat anumber of times in a row It could be typing and formatting a section of text, running aseries of menu commands, or editing a document in a particular way If you’re like mostpeople, when faced with these repetitive chores, you probably find yourself wishing therewas some way to ease the drudgery and reduce the time taken by this mindless but neces-sary work
Sure, most of the Office applications have a Repeat button on the Quick Access Toolbarthat lets you repeat your most recent action That’s handy, but it repeats only a singleaction If you need to repeat two or more actions, this solution doesn’t work
What’s a person to do about this? Well, what if I told you that it was possible to automate
just about any routine and repetitive task? What if I told you that it was possible to take thisautomated task and run it immediately simply by selecting a command or even by justpressing a key or clicking a button?
It sounds too good to be true, I know, but that’s just what Visual Basic for Applications
(VBA) can do for you You use VBA to create something called a macro, which is really just
a series of tasks that you want a program to perform So a macro is not unlike a recipe,which is a set of instructions that tells you what tasks to perform to cook or bake some-thing A macro, too, is a set of instructions, but in this case it tells a program (such as Word
or Excel) what tasks to perform to accomplish some goal
The big difference, however, is that a macro combines all these instructions into a singlescript that you can invoke with a keystroke or just a few mouse clicks In this sense, then, amacro isn’t so much like a recipe for, say, how to bake bread, but is more akin to a breadmachine, which, after it has been loaded with ingredients, bakes a loaf with the push of abutton
This list of instructions is composed mostly of macro statements Some of these statements
perform specific macro-related tasks, but most correspond to the underlying application’scommands and dialog box options For example, in any application, you can close the cur-rent (active) window by selecting the Office menu’s Close command In a VBA macro, thefollowing statement does the same thing:
ActiveWindow.Close
Trang 20What You Should Know Before Reading This Book
What Does VBA Have to Do with Macros?
VBA is a programming language designed specifically for creating application macros Thatsounds intimidating, I’m sure, but VBA’s biggest advantage is that it’s just plain easier to usethan most programming languages If you don’t want to do any programming, VBA enablesyou to record macros and attach them to buttons either inside a document or on the QuickAccess Toolbar (as you’ll see in Chapter 1) You also can create your own dialog boxes by
“drawing” the appropriate controls onto a document Other visual tools enable you to tomize the Ribbon as well, so you have everything you need to create simple scripts withoutwriting a line of code
cus-Of course, if you want to truly unleash VBA’s capabilities, you’ll need to augment your
interface with programming code That sounds pretty fancy, but the VBA language is structed in such a way that it’s fairly easy to get started and to figure things out as you go
con-along More than any other programming language, VBA enables you to do productive
things without climbing a huge learning curve
What You Should Know Before Reading This Book
First and foremost, this book does not assume that you’ve programmed before VBA
begin-ners are welcome here and will find the text to their liking
I’ve tried to keep the chapters focused on the topic at hand and unburdened with
long-winded theoretical discussions For the most part, each chapter gets right down to brass
tacks without much fuss and bother To keep the chapters uncluttered, I’ve made a few
assumptions about what you know and don’t know:
folders
and work with tools such as menus, dialog boxes, and the Help system
mouse, printer, and modem
work with Office 2000, Office XP, and Office 2003 Therefore, I assume you’ve used
these Office programs for a while and are comfortable working with these programs
Trang 21What’s in the Book
This book isn’t meant to be read from cover to cover, although you’re certainly free to dojust that if the mood strikes you Instead, most of the chapters are set up as self-containedunits that you can dip into at will to extract whatever nuggets of information you need.However, if you’re a beginning VBA programmer, I recommend working through Chapters
1 to 6 to ensure that you have a thorough grounding in the fundamentals of the VBA editorand the VBA language
The book is divided into four main parts To give you the big picture before diving in,here’s a summary of what you’ll find in each part:
Part 1, “Getting Started with VBA”—The half dozen chapters in Part 1 give you a
thorough grounding in VBA You start off easy by learning how to create and runrecorded macros, which doesn’t require any programming (Chapter 1) In Chapters 2though 6, you learn the basics of the VBA language, which you’ll use in earnestthroughout the rest of the book
Part 2, “Putting VBA to Work”—The five chapters in Part 2 enable you to put
your VBA programming knowledge to good and practical use by showing you how toprogram the five main Office applications: Word (Chapter 7), Excel (Chapter 8),PowerPoint (Chapter 9), Access (Chapter 10), and Outlook (Chapter 11)
Part 3, “Getting the Most Out of VBA”—The five chapters in Part 3 augment
your VBA toolkit with lots of useful techniques You learn how to interact with users(Chapter 12), how to create custom dialog boxes (Chapter 13), how to create customRibbon tabs and buttons (Chapter 14), how to debug your VBA code (Chapter 15),and how to use VBA to control other applications (Chapter 16)
Appendixes—The book finishes with two appendixes that you can use as a reference.
Appendix A lists all the VBA statements, and Appendix B lists all the VBA functions
This Book’s Special Features
VBA for the 2007 Microsoft Office System is designed to give you the information you need
without making you wade through ponderous explanations and interminable technical ground To make your life easier, this book includes various features and conventions thathelp you get the most out of the book and VBA itself
back-■ Things you type: Whenever I suggest that you type something, what you type appears
in a bold font.
■ Commands: I use the following style for Ribbon commands: View, Macros This
means that you click the Ribbon’s View tab, and then click the Macros button
■ Dialog box controls: Dialog box controls have underlined accelerator keys: Close.
Trang 22This Book’s Special Features
■ Visual Basic keywords: Keywords reserved in the VBA language appear in monospacetype
■ Code-continuation character ( ➥): When a statement is too long to fit on one line of
this book, I break it at a convenient place, and add the code-continuation character atthe beginning of the next line
This book also uses the following boxes to draw your attention to important (or merely
interesting) information
➔ These cross-reference elements point you to related material elsewhere in the book
The Note box presents asides that give you more information about the topic under discussion
These tidbits provide extra insights that give you a better understanding of the task at hand
The all-important Caution box tells you about potential accidents waiting to happen.There are
always ways to mess things up when you’re working with computers.These boxes help you avoid atleast some of the pitfalls
C A U T I O N
Trang 24IN THIS
I
Getting Started with VBA
1 Creating and Running Recorded Macros 3
2 Writing Your Own Macros 15
3 Understanding Program Variables 33
4 Building VBA Expressions 53
5 Working with Objects 71
6 Controlling Your VBA Code 91
Trang 26I N T H I S C H A P T E R
Creating and Running
Recorded Macros
1
This book is about programming, but for certain
tasks you may not need to do any programming at
all That’s because VBA in Word and Excel lets you
create a macro automatically by recording a set of
steps you perform in the program (Unfortunately,
the other programs in the 2007 Office suite don’t
have macro recording capabilities.) This is by far
the easiest way to create a macro With this
method, you start the macro recording feature and
then run through the operations you want to
auto-mate—which can include selecting text, running
commands from the Ribbon (the Office 2007
replacement for the menus and toolbars in previous
versions of Office), and choosing dialog box
options The macro recorder takes note of
every-thing you do, translates everyevery-thing into the
appro-priate VBA programming statements, and stores
them where you can easily rerun the macro later
on If you’re just starting out with VBA (or
pro-gramming in general), recording macros is a great
way to get your feet wet because you never have to
work with or even see a single line of programming
code
Recording a VBA Macro 5 Running a Recorded Macro 8
Even if you’re an experienced programmer and plan only to write
your own VBA code, you should still know how to record macros
That’s because it’s often easiest to begin a VBA procedure by
record-ing some of the actions you need.This way,VBA does much of the
work for you, and you can then tweak the resulting code by hand
Trang 27What kinds of things should you record? Just about any operation that’s lengthy—it could
be either a single complex task or multiple, related tasks—or tedious, and that you performrelatively often You can probably think of several operations right off the bat Here arefour common ideas:
■ Multiple find and replace actions—It’s common in business to get a document that
requires a number of adjustments throughout: converting one style to another, ing formatting, deleting extra line breaks, changing two spaces after each sentence toone space, and so on Each of these operations requires a separate Replace command.That’s fine for one document, but if you have a number of documents or documentsthat you receive regularly, the task becomes inefficient and tedious You can avoid thedrudgery by recording all the Replace operations to a single macro, and then runningthat macro each time you receive a document that requires those adjustments
remov-■ Automate repetitive steps—Working with certain documents, you may find that you
need to run certain steps to fix or adjust text For example, the paragraphs in a ment may all be indented by, say, five spaces rather than a First Line Indent marker onthe Ruler If the document consists of dozens of paragraphs, adjusting them all by hand
docu-is no one’s idea of fun However, it would be easy to record a macro that moves to thestart of the paragraph, deletes the five spaces, and then applies the first line indent Ifyou assign a shortcut key or Quick Access toolbar button to the macro, you can runthrough all the paragraphs very quickly
■ Window adjustments—Unless you run all your documents maximized, you probably
have a certain spot on the screen where you like to work For example, you might wantyour document windows adjusted so that you can see your Outlook window and moni-tor incoming email while you work Similarly, you might prefer that your documentsuse the most vertical room possible, which means adjusting the size so that the top isflush with the top of the screen, and the bottom is flush with the Windows taskbar.These position and size adjustments aren’t difficult, but if you regularly work withdozens of documents during the day, it can be a pain to be constantly tweaking thewindow as you open each document A better idea is to record the window adjustments
to a macro and then run that macro each time you open a document
■ Common steps for new documents—It’s quite common to have to run several steps
with some or all of the new documents you create In Word, for example, when youcreate a new document you might always insert a certain cover page, activate theDocument Map, switch to Draft view, and display the Document Properties informa-tion panel so you can set the document’s Title, Subject, and Keywords Depending onthe number of tasks you run, all this can take a number of minutes By recording thesame steps to a macro, however, you can perform them in seconds and with just a fewmouse clicks or a single keystroke
Recording macros is endlessly useful, and after you get the hang of it, you’ll likely findyourself recording all kinds of routine operations (and therefore saving yourself tons oftime, to boot)
1
Trang 28Recording a VBA Macro
Recording a VBA Macro
As I mentioned earlier, only Word and Excel come with the Record Macro command,
which is a shame (In Office 2003, you could record macros in PowerPoint, too.) However,these two programs are the most suited to recording macros, so it’s not all that surprising
that Microsoft has restricted the Office macro recording capabilities The next two sectionsshow you how to record a macro in Word and Excel
Recording a Word Macro
Before getting started, make sure that Word is set up so that it’s ready to record If you
want to perform your actions on a specific document, for example, make sure that
docu-ment is open Similarly, if you want to record a series of formatting options, select the textyou want to work with Here are the steps to follow to record a macro in Word:
also click the Macro Recording button in the status bar If you don’t see the Macro
Recording button, right-click the status bar and then click Macro Recording.) The
Record Macro dialog box appears, as shown in Figure 1.1
1
Figure 1.1
Use Word’s version of the
Record Macro dialog box
to name and describe
your macro
Name text box to change the name to something more meaningful However, you
must follow a few naming conventions:
• No more than 255 characters (That sounds like a lot, and it is Because you mayoccasionally have to type macro names, I recommend keeping the names rela-
tively short to save wear and tear on your typing fingers.)
• The first character must be a letter or an underscore (_)
• No spaces or periods are allowed
Trang 293. Use the Store Macro In drop-down list to specify where the macro will reside I ommend keeping the default All Documents (Normal.dotm) option This saves themacro in the Normal template, which makes it available all the time (You can alsostore the macro in any open template, which makes the macro available to any docu-ment that uses the template, or in any open document, which makes the macro avail-able only to that document.)
mind during the recording:
• Word gives you two indications that a recording is in progress (see Figure 1.2):the mouse pointer includes what looks like a cassette tape icon, and the statusbar’s Record Macro button changes to a blue square
• The mouse works only for selecting Ribbon commands and dialog box options
If you need to change the document cursor position or select text, you need touse the keyboard
• Because the macro recorder takes note of everything you do, be careful not to
perform any extraneous keyboard actions or mouse clicks during the recording
1
You’ll see later on that one way to run a recorded macro is to select it from a list of all your recordedmacros If you create a lot of macros this way, that list will get long in a hurry.Therefore, when nam-ing your recorded macros, make sure you assign names that will make it easy to differentiate onemacro from another Names such as Macro1andMacro2tell you nothing, but names such as
AdjustWindowSizeandNewDocumentTasksare instantly understandable
the mouse pointer
and Record Macro
button
Mouse pointer Record Macro button
Trang 30Recording a VBA Macro
Stop Recording (or click the Macro Recording button in the status bar)
Recording an Excel Macro
Before launching your recording in Excel, make sure the program is set up as required Forexample, open the workbook and select the worksheet you want to use during the record-ing Here are the steps to follow to record a macro in Excel:
also click the Macro Recording button in the status bar.) The Record Macro dialog
box appears Figure 1.3 shows the Excel version
1
Figure 1.3
Use Excel’s Record Macro
dialog box to name and
describe your macro
descrip-tive (Follow the same naming conventions as I outlined in the previous section.)
macro Note, however, that this is optional because VBA offers other ways to run yourrecorded macros (see “Running a Recorded Macro,” later in this chapter)
store the macro in the current workbook, a new workbook, or in the Personal Macro
Workbook If you use the Personal Macro Workbook, your macros will be available toall your workbooks
Excel’s Personal Macro Workbook doesn’t exist until you assign at least one recorded macro to it
After you do that, the Personal Macro Workbook (its filename is PERSONAL.XLSB) opens cally every time you start Excel.This is useful because any macros contained in this file will be avail-able to all your workbooks, which makes them easy to reuse Note, however, that you don’t see thePersonal Macro Workbook when you start Excel because the file is hidden If you want to see thisworkbook, you have to first unhide it: Choose the View, Unhide command, select Personal in theUnhide dialog box, and then click OK
Trang 315. Enter an optional description of the macro in the Description text box.
mind during the recording:
• Excel gives you just one indication that a recording is in progress: The statusbar’s Record Macro button changes to a blue square (see Figure 1.2, earlier)
• Unlike Word, Excel makes the mouse available for all actions
• Because the macro recorder takes note of everything you do, be careful not to
perform any extraneous keyboard actions or mouse clicks during the recording
Stop Recording (or click the Macro Recording button in status bar)
Running a Recorded Macro
In almost all cases, you record a macro so that you can run it again in the future, probably anumber of times depending on the tasks you recorded (The exception would be, as I men-tioned earlier, if you record a macro to use as a starting point for writing your own code.)
So after you record a macro, how do you get it to run again? There are three main ods you can use: the Macro Name list, a shortcut key, and a Quick Access toolbar button
meth-Using the Macro Name List
The Macro Name list is a listing of all your recorded macros (It also contains macros youcreate by hand, as discussed in the next chapter.) This means that all your recorded macrosare as little as four mouse clicks away, as you see in the following steps:
run (for example, open a document, move the cursor into position, or select text)
Figure 1.4), although in Excel it’s called the Macro dialog box
macro
1
Trang 32Running a Recorded Macro
Assigning Shortcut Keys to Recorded Word Macros
If you have a recorded macro that you’ll be using frequently, even the few mouse clicks
required to run the macro from the Macro Name list can seem excessive A faster tive is to assign a shortcut key to the macro, which means you can run the macro by press-ing the shortcut key
alterna-To assign a shortcut key in Word, follow these steps:
• If you haven’t recorded the macro yet, choose View, pull down the Macros list,
and then choose Record Macro Fill in the macro details (name, storage location,and description) first, and then click Keyboard Skip to step 4
• If you’ve already recorded the macro, choose Office, Word Options, click ize, and then click the Customize button beside the Keyboard Shortcuts text
displays your macros in the Macros list
to use One of two things will happen:
Figure 1.5 This means no other command is using the shortcut key, so proceed
to step 5
1
Figure 1.4
Use the Macro Name list
to select the macro you
want to run
Trang 33• Word displays Currently Assigned To, followed by the name of a command.This means that another Word command (or macro) is already using the short-cut key Repeat step 4 until you find an unassigned shortcut key.
C A U T I O N
Assigning Shortcut Keys to Recorded Excel Macros
If you want to assign a shortcut key to a recorded Excel macro, you have two ways to getstarted:
then choose Record Macro Fill in the macro details (name, storage location, anddescription) first, and then click Keyboard Skip to step 4
If you have trouble remembering your keyboard shortcuts, you can get Word to print out a list ofthem Choose Office, Print to open the Print dialog box In the Print What list, click Key Assignments,and then click OK
Trang 34Running a Recorded Macro
the Macro dialog box Click the macro you want to work with and then click Options
to display the Macro Options dialog box shown in Figure 1.6
1
Figure 1.6
Use the Macro Options
dialog box to assign a
shortcut key to a macro
In the Shortcut Key Ctrl+ text box, type the letter you want to use with Ctrl for the key
Click OK
Excel shortcut keys are case sensitive, meaning you can create separate shortcuts with uppercaseand lowercase letters For example, if you type einto the Ctrl+ text box, you have to press Ctrl+E(or, to be precise, Ctrl+e) to run the macro However, if you type Einto the Ctrl+ text box, you have
to press Ctrl+Shift+E to run the macro
Creating a Quick Access Toolbar Button for a Recorded Macro
The only problem most people have with assigning shortcut keys to macros is ing which shortcut runs which macro! The more shortcuts you assign, the harder it gets toremember them all and the more likely it is that you’ll press an incorrect shortcut key by
remember-mistake What many VBA veterans do is assign just a few shortcut keys to their most
fre-quently used macros, and other macros that they need handy they assign to the Quick
Make sure you don’t specify a shortcut key that conflicts with Excel’s built-in shortcuts (such asCtrl+B for Bold or Ctrl+C for Copy) If you use a key that clashes with an Excel shortcut, Excel over-rides its own shortcut and runs your macro instead (provided that the workbook containing themacro is open)
There are only four letters not assigned to Excel commands that you can use with your macros: e, j,
m, and q You can get extra shortcut keys by using uppercase letters Note, however, that Excel usesfour built-in Ctrl+Shift shortcuts: A, F, O, and P
C A U T I O N
Trang 35Access toolbar This is a great way to run oft-used macros because they’re only a click awayand you can assign different icons to each macro to help you differentiate them.
Follow these steps in either Word or Excel to create a Quick Access toolbar button for amacro:
The application’s Options dialog box appears with the Customize tab displayed
macro to the list of Quick Access toolbar buttons
buttons and then click Modify The Modify Button dialog box appears, as shown inFigure 1.7
1
Figure 1.7
Use the Modify
Button dialog box to
assign an icon and
display name to your
macro button
the mouse pointer over the button
Trang 36Running a Recorded Macro
From Here
pro-cedures and enter your own VBA statements in Chapter 2, “Writing Your Own
Macros.”
that in Chapter 3, “Understanding Program Variables.”
“Building VBA Expressions,” to learn more
in Chapter 5, “Working with Objects.” Also, see Part II, “Putting VBA to Work,” to
get the specifics on the objects used in Word, Excel, and other Office applications
that control program flow I discuss these statements in Chapter 6, “Controlling YourVBA Code.”
1
In its default position above the Ribbon, the Quick Access toolbar can display only so many buttons
If you want to add lots of buttons for your macros (or other program commands), move the QuickAccess toolbar below the Ribbon Click the Customize Quick Access Toolbar button and then chooseShow Below the Ribbon
Trang 38I N T H I S C H A P T E R
Writing Your Own Macros
2
Letting VBA do all the work by recording your
macros is an easy way to automate tasks, and it’s a
technique you’ll use often However, to get the
most out of VBA you need to do some full-fledged
programming, which means writing your own
macros, either from scratch or by using a recorded
macro as a starting point
Why go to all that trouble? Here are just a few of
the advantages you gain by doing this:
particularly one that requires a large number of
steps, you can make a simple edit to the
macro’s VBA code to fix the mistake rather
than re-record the whole thing from scratch
means you ensure that your macros do exactly
what you need them to do
VBA to manipulate the Office programs and to
perform some impressive programming feats
that are simply not available via the recording
process
To help you realize these advantages and many
more, this chapter introduces you to the basics of
writing simple procedures and functions, as well as
how to get around in the Visual Basic Editor, which
is the tool that VBA provides for writing macros by
hand This sets the stage for the next few chapters,
where I take a closer look at the specifics of the
VBA language
Activating the Ribbon’s Developer Tab 16 Displaying the Visual Basic Editor 16 Touring the Visual Basic Editor 17 Understanding VBA Procedures 19 Creating a Command Macro 19 Creating a User-Defined Function 23 Taking Advantage of IntelliSense 27 Shutting Down the Visual Basic Editor 30
Trang 39Activating the Ribbon’s Developer Tab
If you’ll be writing VBA code regularly, you can make some coding chores a bit more cient by displaying the new Developer tab in the Office 2007 Ribbon This tab gives youone-click access to many VBA-related features, so it’s worth displaying Follow these steps:
program, such as Word or Excel)
some VBA features
Displaying the Visual Basic Editor
To get the Visual Basic Editor onscreen in any Office program, choose Developer, VisualBasic (Note, however, that for simplicity’s sake, I use a single Office application—Excel—for the examples throughout this chapter.) Figure 2.2 shows the new window that appears(although bear in mind that the window you see may be slightly different)
You can also get to the Visual Basic Editor by pressing Alt+F11 In fact, this key combination is a gle that switches you between the Visual Basic Editor and the current Office program
Trang 40Touring the Visual Basic Editor
Touring the Visual Basic Editor
The idea behind the Visual Basic Editor is simple: It’s a separate program that’s designed to
do nothing else but help you create and edit VBA macros (In professional programming
circles, the Visual Basic Editor is called an integrated development environment or IDE.)
When you open the Visual Basic Editor for the first time, you don’t see much The left side
of the editor has two windows labeled Project and Properties The latter you don’t need toworry about right now (I’ll talk about it in Chapter 5, “Working with Objects.”) The
Project window (technically, it’s called the Project Explorer) shows you the contents of the
current VBA project In simplest terms, a project is an Office file and all its associated VBA
items, including its macros and its user forms (You learn about user forms in Chapter 12,
“Creating Custom VBA Dialog Boxes.”)
Creating a New Module
You do most of your work in the Visual Basic Editor within one or more modules, which are
windows designed to hold programming code You may already have an existing module ifyou recorded some macros in the previous chapter Just in case, here are the steps to follow
to create a new module:
project into which you want to insert the new module Here are some notes to bear inmind:
• In Word, if you want the new module’s macros to be available all the time, clickthe Normal project (this adds the module to the Normal template)
2
Figure 2.2
You use the Visual Basic
Editor to craft and edit
your macros