4. Dedication
To my mother and my mother-in-law, Genowefa Malinowska and
Alfreda Korol. They have always been against the long hours and long
nights it takes to write technical books. My life may not have been very
comfortable during the past 10 years (I certainly could have slept more
and relaxed more, and tried all the other highly recommended things);
however, the decade that I’ve dedicated to writing so that others can
benefit may be that special mission I was born to complete. Hey, you
never know.
13. Contents
Creating a Virtual Directory . . . . . . . . . . . . . . . . . . . . . . . . 505
Running Your First ASP Script . . . . . . . . . . . . . . . . . . . . . . . 508
Generating a Tab-delimited File on the Web Server. . . . . . . . . . . . 509
Creating an Excel File from User Input . . . . . . . . . . . . . . . . . . 514
Printing Excel Data to an Internet Browser
using the GetString Method . . . . . . . . . . . . . . . . . . . . . . . 523
Creating Charts in ASP. . . . . . . . . . . . . . . . . . . . . . . . . . . 525
What’s Next... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 530
Chapter 17 XML and Excel 2002 . . . . . . . . . . . . . . . . . . . . . . 531
What is XML? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 532
XML Support in Excel 2002 . . . . . . . . . . . . . . . . . . . . . . . . . . 533
Creating XML Spreadsheet Files with VBA. . . . . . . . . . . . . . . . . . 534
Viewing the XML Source File in Notepad. . . . . . . . . . . . . . . . . . . 536
Well-Formed XML Documents . . . . . . . . . . . . . . . . . . . . . . . . 539
Viewing the XML Source File in Internet Explorer. . . . . . . . . . . . . . 540
Building XML Files Outside of Microsoft Excel 2002. . . . . . . . . . . . . 542
The XML Flattener . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 543
Formatting XML Data with Stylesheets. . . . . . . . . . . . . . . . . . . . 545
Linking an XML Document to a Stylesheet. . . . . . . . . . . . . . . . . . 550
Viewing XML Documents Formatted with Stylesheets. . . . . . . . . . . . 550
Using an XSLT Template . . . . . . . . . . . . . . . . . . . . . . . . . . . 553
XML Data Islands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 555
Using VBScript to Transform the Contents of XML Data Islands. . . . . 557
Saving a Range of Cells as an XML Document . . . . . . . . . . . . . . . . 559
The XML Document Object Model . . . . . . . . . . . . . . . . . . . . . . 561
Transform XML into HTML with an XSL Stylesheet Programmatically . 563
Using VBScript and XML DOM to Transform XML Documents . . . . . 566
Working with XML Document Nodes . . . . . . . . . . . . . . . . . . . 567
Retrieving Information from Element Nodes . . . . . . . . . . . . . . . 569
XMLviaADO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 573
Saving an ADO Recordset as XML to Disk . . . . . . . . . . . . . . . . 573
Two Types of XML Files . . . . . . . . . . . . . . . . . . . . . . . . . . 574
Applying an XSL Stylesheet . . . . . . . . . . . . . . . . . . . . . . . . 576
Transforming Attribute-Based XML Data into an HTML Table. . . . . . 578
Loading an ADO Recordset . . . . . . . . . . . . . . . . . . . . . . . . 580
Saving the ADO Recordset to XML in Memory . . . . . . . . . . . . . . 581
Saving the ADO Recordset into the XML DOMDocument Object . . . . 584
XMLandASP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 586
Posting Excel XML Data to a Web Server. . . . . . . . . . . . . . . . . . . 591
What’s Next… . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 613
Appendix A—Programming PivotTables and PivotCharts . . . . . . . . . . 615
Appendix B—Programming Special Features. . . . . . . . . . . . . . . . . 643
Appendix C—Introduction to Using and Programming Smart Tags . . . . . 661
Appendix D—Microsoft Office XP Web Components. . . . . . . . . . . . . 675
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 698
xii
14. Acknowledgments
I would like to express my grateful appreciation to all the people involved
in the creation of this book. Special thanks go to Wordware Publishing, Inc.
editors Beth Kohler and Heather Hill for their help, comments, and thor-ough
review of this book. It was a pleasure to work with you ladies. Your
queries were so skillfully put together that I’ve decided to bind them for
future reference.
Many thanks to Wes Beckwith for all his efforts and patience in coordi-nating
this project.
To Witold Sikorski of Mikom Publishing, Warsaw, Poland, a big thank
you for introducing me to Jim Hill of Wordware Publishing, Plano, Texas.
Needless to say, if these two hadn’t met several years ago at a book fair in
Frankfurt, Germany, I would have never become a bilingual author.
A special thanks goes to Terrence Joubert for taking the time to review
several chapters from the previous version of this book (Learn Microsoft
Excel 2000 VBA Programming) and for his list of suggestions to include in
this new release. Due to time constraints and the size of the book, I could
not implement all of his great suggestions. I am looking forward to Ter-rence’s
book, ADO .NET Programming, also from Wordware Publishing.
Thanks to the readers of the previous version of this book for their
praise and criticism. I’m happy to hear that so many of you have found the
book very useful in self-teaching Excel VBA programming. I apologize to
those of you who have found some subjects missing or not adequately cov-ered.
I have tried to do a better job this time; however, please keep in mind
this book isn’t a know-it-all reference but a step-by-step manual. To take
you through the subjects in an easy-to-follow manner I had to make choices
as to what goes in and what’s not covered.
To my close friends, Ludmila Larmor, Jolanta and Dariusz Partyka, and
Mariola Weyna for their encouragement and support.
Finally, I’d like to thank my husband, Paul, simply for being my husband
and sharing with me the same fields of interest. Paul has been gaining expe-rience
with the .NET technology while I was busy writing.
xiii
16. Introduction
This book shows you what’s doable with Microsoft Excel 2002 beyond the
standard user interface. If you ever wanted to open a new worksheet with-out
using the menu or create a fully automated custom form to gather data
and store the results in a spreadsheet, you’ve got to learn some program-ming.
This book shows you how to become more productive by delegating
many time-consuming and repetitive tasks to Excel. Using Excel’s built-in
language, VBA (Visual Basic for Applications), you can bring a lot of auto-mating
power to your spreadsheets, whether you are creating them for
yourself or others. By using a number of built-in programming tools, you
can work smarter than you ever thought possible. There is no extra cost
except for your willingness to become familiar with a secret window behind
the Microsoft Excel application window. For a quick peek, while in Excel,
hold down Alt while pressing F11. You will end up in the Visual Basic Editor
(VBE) screen—Excel’s programming interface.
Now that this well-guarded secret is out, let me tell you more. Apart
from VBA, this book introduces you to two hot Internet technologies that
can be used with Microsoft Excel. One is ASP (Active Server Pages) and
the other is XML (Extensible Markup Language). You also learn a number
of other supporting technologies. So, if you really want to gain some hot
skills, purchase this book and waste no time beginning studying.
Learn Microsoft Excel 2002 VBA Programming with XML and ASP
leads you through the process of creating VBA procedures, VBScripts, ASP
pages, XML documents, and XSL stylesheets from start to finish. Along the
way, there are detailed, practical “how-to” examples and plenty of illustra-tions.
The book’s approach is to learn by doing. This book begins by
addressing basic VBA concepts in the early chapters and progresses to
more complex topics in later chapters. Each of the 17 chapters should be
worked through in order. In addition, there are four appendices that discuss
working with and programming special features in Excel. Consider this
book as a sort of private course that you can attend in the comfort of your
office or home.
xv
17. Introduction
Some courses have prerequisites and so does this one. Learn Microsoft
Excel 2002 VBA Programming with XML and ASP does not explain to the
user how to use Excel features such as menus and keyboard shortcuts. The
book assumes that you are comfortable working with an Excel spreadsheet
and are interested in becoming more productive by learning how to commu-nicate
with Excel in its own language and learning how to integrate it with
the current Internet technologies.
xvi
18. Chapter 1
Introduction to
Spreadsheet
Automation
Understanding Macros Common Uses for Macros
Planning a Macro Recording a Macro Running the
Macro Modifying the Macro Adding Comments
Analyzing the Macro Code Cleaning Up the Macro
Code Testing the Modified Macro Two Levels of
Macro Execution Improving Your Macro Renaming
the Macro Other Methods of Running Macros
Saving Macros Printing Macros Storing Macros in
the Personal Macro Workbook Opening Workbooks
Containing Macros The Visual Basic Editor Window
Understanding the Project Explorer Window Under-standing
the Properties Window Understanding the
Code Window Other Windows in the Visual Basic Edi-tor
Window What’s Next...
1
19. 2 Chapter 1: Introduction to Spreadsheet Automation
Are you ready to build intelligence into your Microsoft Excel 2002 spread-sheets?
By automating routine tasks, you can make your spreadsheets
quicker and more efficient. This first chapter walks you through the process
of speeding up spreadsheet tasks with macros. You learn what macros are,
how and when to use them, and how to write and modify them. Getting
started with macros is easy. Creating them requires nothing more than what
you already have—a basic knowledge of Microsoft Excel 2002 menus and
spreadsheet concepts. Are you ready to begin? Make sure you are seated at
a computer and launch Microsoft Excel 2002.
Understanding Macros
Macros are programs that store a series of commands. When you create a
macro, you simply combine a sequence of keystrokes into a single command
that you can later “play back.” Because macros can reduce the number of
steps required to complete tasks, using macros can significantly decrease
the time you spend creating, formatting, modifying, and printing your
worksheets.
You can create macros by using Microsoft Excel’s built-in recording
tool, or you can write them from scratch by using the Visual Basic Editor.
Microsoft Excel 2002 macros are created with the powerful programming
language Visual Basic for Applications, commonly known as VBA.
Tip 1-1: The Common Language
Excel 5 was the first application on the market to feature Visual Basic
for Applications. Since then, VBA has made its way into all Microsoft
Office applications. This means that what you learn about VBA in this
book can be used later in creating macros automating other Microsoft
Office products such as Word, PowerPoint, Outlook or Access.
Common Uses for Macros
Microsoft Excel 2002 comes with dozens of built-in, timesaving features
that allow you to work faster and smarter. Before you decide to automate a
worksheet task with a macro, make sure there is not already a built-in fea-ture
that you can use to perform that task. Consider, however, creating a
macro when you find yourself performing the same series of actions over
and over again or when Excel does not provide a built-in tool to do the job.
Macros enable you to automate just about any part of your spreadsheet.
For example, you can automate data entry by creating a macro that enters
headings in a worksheet or replaces column titles with new labels. Macros
also enable you to check for duplicate entries in a selected area of your
worksheet. With a macro, you can quickly apply formatting to several
20. Chapter 1: Introduction to Spreadsheet Automation 3
worksheets, as well as combine different formats, such as fonts, colors, bor-ders,
and shading. Even though Excel has an excellent chart facility, macros
are the way to go if you wish to automate the process of creating and for-matting
charts. Macros will save you keystrokes when it comes to setting
print areas, margins, headers, and footers, and selecting special print
options for printouts.
Planning a Macro
Before you create a macro, take a few minutes to consider what you want to
do. Because a macro is a collection of a fairly large number of keystrokes, it
is important to plan your actions in advance. The easiest way to plan your
macro is to manually perform all the actions that the macro needs to do. As
you enter the keystrokes, write them down on a piece of paper exactly as
they occur. Don’t leave anything out. Like a voice recorder, Microsoft
Excel’s macro recorder records every action you perform. If you do not plan
your macro prior to recording, you will end up with unnecessary actions
that will slow it down. Although it’s easier to edit a macro than it is to erase
unwanted passages from a voice recording, performing only the actions you
want recorded will save you editing time and trouble later.
Suppose you want to see at a glance which areas of a worksheet are
text, numbers, and formulas. Figure 1-1 shows a simple spreadsheet for-matted
with distinct font colors and styles to help identify the contents of
the underlying cells.
Figure 1-1:
Finding out “what’s what” in a
spreadsheet is easy with
formatting applied by an Excel
macro.
To produce the formatting results shown in Figure 1-1, open any existing
spreadsheet that contains calculations or create the one shown in the figure.
If you decide to use the worksheet example in the above figure, make sure
you use the SUM function to calculate the monthly and quarterly totals.
Before you record the macro, manually perform the following actions:
1. Select a single cell.
2. Select Edit | Go To.
3. In the Go To dialog box, click the Special button.
21. 4 Chapter 1: Introduction to Spreadsheet Automation
4. In the Go To Special dialog box, click the Constants option button and
then remove the check mark next to Numbers, Logicals, and Errors.
Only the Text check box should be checked.
5. Click OK to return to the worksheet. Notice that the cells containing
text are now selected. Be careful not to change your selection until you
apply the necessary formatting in the next step.
6. With the text cells still selected, choose Format | Cells.
7. In the Format Cells dialog box, click the Font tab. Set the Font style to
Bold and the Color to Violet. Then click OK to close the dialog box.
Notice that the cells containing text now appear in a different color.
Steps 1 to 7 allowed you to locate all the cells that contain text. To select
and format cells containing numbers, perform the following actions:
8. Select a single cell.
9. Select Edit | Go To.
10. In the Go To dialog box, click the Special button.
11. In the Go To Special dialog box, click the Constants option button and
remove the check mark next to Text, Logicals, and Errors. Only the
Numbers check box should be checked.
12. Click OK to return to the worksheet. Notice that the cells containing
numbers are now selected. Be careful not to change your selection until
you apply the necessary formatting in the following step.
13. With the number cells still selected, choose Format | Cells.
14. On the Font tab of the Format Cells dialog box, set the Color to Dark
blue. Then click OK to close the dialog box.
Steps 8 to 14 took care of locating and formatting cells with numbers. To
select and format cells containing formulas, perform the following actions:
15. Select a single cell.
16. Select Edit | Go To.
17. In the Go To dialog box, click the Special button.
18. In the Go To Special dialog box, click the Formulas option button.
19. Click OK to return to the worksheet. Notice that the cells containing
numbers that are results of formulas are now selected. Be careful not to
change your selection until you apply the necessary formatting in the
next step.
20. With the formula cells still selected, choose Format | Cells.
21. On the Font tab of the Format Cells dialog box, set the Font style to
Bold and the Color to Red. Then click OK to close the dialog box.
22. Chapter 1: Introduction to Spreadsheet Automation 5
Steps 15 to 21 allowed you to locate and format cells containing formulas.
To make it easy to understand all the formatting applied to the worksheet’s
cells, you will now add the color legend.
22. Select cells A1:A3 and choose Insert | Rows.
23. Select cell A1.
24. Choose Format | Cells, and on the Patterns tab click the Purple color
in the Cell shading box. Click OK to return to the worksheet.
25. Select cell B1 and type Text.
26. Select cell A2.
27. Choose Format | Cells, and click the Dark blue color in the Cell
shading box. Click OK to return to the worksheet.
28. Select cell B2 and type Numbers.
29. Select cell A3.
30. Choose Format | Cells, and click the Red color in the Cell shading
box. Click OK to return to the worksheet.
31. Select cell B3 and type Formulas.
32. Select cell A1.
After completing steps 22 to 32, cells A1:A3 will display a simple color leg-end,
as shown in Figure 1-1.
As you can see, no matter how simple your spreadsheet task appears at
first, many steps may be required to get exactly what you want. Creating a
macro that is capable of playing back your keystrokes can be a real
time-saver, especially when you have to repeat the same process for a num-ber
of worksheets.
Recording a Macro
Now that you know what actions you need to perform, it’s time to turn on
the macro recorder and create your first macro.
Before you follow the recording steps outlined below, be sure to
remove the formatting from the example worksheet. To do this, press
Ctrl+A to select the entire worksheet. Then choose Edit | Clear | For-mats.
Select cells A1:A3 and choose Edit | Delete. In the Delete dialog box,
select the Entire row option button. Then click OK.
To create your first macro, follow these steps:
1. Select a single cell.
Before you record a macro, you should decide whether or not you want
to record the positioning of the active cell. If you want the macro to
always start in a specific location on the worksheet, turn on the macro
recorder first and then select the cell you want to start in. If the loca-tion
of the active cell does not matter, select a single cell first and then
turn on the macro recorder.
23. 6 Chapter 1: Introduction to Spreadsheet Automation
2. Choose Tools | Macro | Record New Macro. The Record Macro dia-log
box appears.
Figure 1-2:
When you record a new macro, you
must name it. In the Record Macro
dialog box you can also supply a
shortcut key, the storage location, and a
description for your macro.
3. Enter the name WhatsInACell for the sample macro.
Tip 1-2: Macro Names
If you forget to enter a name for the
macro, Excel assigns a default name
such as Macro1, Macro2, and so on.
Macro names can contain letters,
numbers, and the underscore
character, but the first character must
be a letter. For example, Report1 is a
valid macro name, while 1Report is not.
Spaces are not allowed. If you want a
space between the words, use the
underscore. For example, instead of
WhatsInACell, enter Whats_In_A_Cell.
4. Select This Workbook in the Store macro in list box.
Tip 1-3: Storing Macros
Excel allows you to store macros in
three locations:
Personal Macro Workbook –
Macros stored in this location will be
available each time you work with
Microsoft Excel. Personal Macro
Workbook is located in the XLStart
folder. If this workbook doesn’t
already exist, Excel creates it the
first time you select this option.
New Workbook – Excel will place
the macro in a new workbook.
This Workbook – The macro will be
stored in the workbook you are cur-rently
using.
5. Enter the following text in the Description box: Indicates the con-tents
of the underlying cells: text, numbers, formulas.
6. Choose OK to close the Record Macro dialog box and begin recording.
The Stop Recording toolbar appears. The status bar at the bottom of
the Excel application window displays “Ready Recording.”
24. Chapter 1: Introduction to Spreadsheet Automation 7
Figure 1-3:
The Stop Recording toolbar has
buttons that allow you to stop the
macro recorder or indicate how Excel
should handle cell addressing when
recording.
Relative Reference
Stop Recording
Tip 1-4: Cell Addressing in Macros: Relative or Absolute?
Absolute – If you want your macro
to execute the recorded action in a
specific cell, no matter what cell is
selected during the execution of the
macro, use absolute cell addressing.
Absolute cell references have the
following form: $A$1, $C$5, etc. By
default, the Excel macro recorder
uses absolute references. Before
you begin to record, make sure the
Stop Recording toolbar’s second
button is not depressed. When you
point the mouse to this button, its
tool tip should read “Relative
reference.”
Relative – If you want your macro to
perform the action in any cell, turn
on the relative references. Relative
cell references have the following
form: A1, C5, etc. Before you begin
to record, make sure the Stop
Recording toolbar’s second button is
depressed. Bear in mind, however,
that Excel will continue recording
using the relative cell references
until you exit Microsoft Excel or click
the Relative Reference button again.
During the process of recording your
macro, you may use both methods of
cell addressing. For example, you may
select a specific cell (e.g., $A$4),
perform an action, then choose another
cell relative to the selected cell (e.g.,
C9, which is located five rows down
and two columns to the right of the
currently active cell $A$4).
Relative references automatically
adjust when you copy them, and
absolute references don't.
7. Perform the actions you have tried out manually in the previous section
(see “Planning a Macro”).
As you record your macro, only the actions finalized by pressing Enter
or clicking OK are recorded. If you press the Esc key or click Cancel
before completing the entry, the macro recorder does not record that
action.
8. When you have performed all the actions, click the Stop Recording
button on the Stop Recording toolbar or choose Tools | Macro | Stop
Recording.
25. 8 Chapter 1: Introduction to Spreadsheet Automation
Running the Macro
After you create a macro, you should run it at least once to make sure it
works correctly. Later in this chapter you will learn various ways to run
macros, but for now, use the menu command.
To see the results of your macro, be sure to remove the formatting
from the example worksheet. To do this, press Ctrl+A to select the entire
worksheet, and then choose Edit | Clear | Formats. Select cells A1:A3 and
choose Edit | Delete. In the Delete dialog box, select the Entire row option
button. Then click OK. Later on you can record the steps of clearing the
worksheet formats in a separate macro.
1. Open any worksheet containing text, numbers, and formulas.
2. Choose Tools | Macro | Macros to open the Macro dialog box.
3. Click the name of the macro you want to run (see Figure 1-4).
4. Choose Run to execute the macro.
Quite often, you will notice that your macro does not perform as expected
the first time you run it. Perhaps during the macro recording you selected
the wrong font or forgot to change the cell color or maybe you just realized
it would be better to include an additional step. Don’t panic. Excel makes it
possible to modify the macro without forcing you to go through the tedious
process of recording your keystrokes again.
Modifying the Macro
Figure 1-4:
In the Macro dialog box you
can select a macro to run,
edit, or delete.
Before you can modify your macro, you must find the location where the
macro recorder placed its code. As you recall, when you turned on the
macro recorder, you selected This Workbook for the location. The easiest
way to find your macro is by opening the Macro dialog box shown in
Figure 1-4.
26. Chapter 1: Introduction to Spreadsheet Automation 9
1. Choose Tools | Macro.
2. Select the name of the macro (WhatsInACell, in this case).
3. Click the Edit button.
Microsoft Excel opens a special window called Visual Basic Editor (also
known as VBE), as shown in Figure 1-5. Using the keyboard shortcut
Alt+F11, you can quickly move between the Microsoft Excel application
window and the Visual Basic Editor window. Now take a moment and try
moving between both windows. To close the Visual Basic Editor window,
select Close on the VBE File menu and return to Microsoft Excel.
Don’t worry if the Visual Basic Editor window seems a bit confusing at
the moment. As you work with the recorded macros and start writing your
own VBA procedures from scratch, you will become familiar with all the
elements of this screen. For now, take a look at the menu bar and toolbar in
the Visual Basic Editor window. Both of these tools differ from the ones in
the Microsoft Excel window. The Visual Basic menu bar and toolbar contain
tools required for programming and testing your VBA procedures. As you
work through the individual chapters of this book, you will become an
expert in using these tools.
Figure 1-5: The Visual Basic Editor window is used for editing macros as well
as writing new procedures in Visual Basic for Applications (VBA).
The main part of the Visual Basic Editor window is a docking surface
for various windows that you will find extremely useful during the course of
creating and testing your VBA procedures. Figure 1-5 displays three win-dows
that are docked in the Visual Basic Editor window: the Project
27. 10 Chapter 1: Introduction to Spreadsheet Automation
window, the Properties window, and the Code window. The Project window
shows an open Module folder in which Module1 is selected. Excel records
your macro actions in special worksheets called Module1, Module2, and so
on. In the following chapters of this book, you will use modules to write the
code of your own procedures. A module resembles a blank document in
Microsoft Word. Individual modules are stored in folders called modules.
Tip 1-5: Macro or Procedure?
A macro is a series of commands or
functions recorded with the help of a
built-in macro recorder or entered
manually in a Visual Basic module.
Beginning with Excel 5.0, the term
“macro” is often replaced with the
broader term “procedure.” Although the
words can be used interchangeably,
many programmers are in favor of
The Code window (see Figure 1-5) displays the following code created by
the macro recorder:
Sub WhatsInACell()
'
' WhatsInACell Macro
' Macro recorded 5/31/2002 by Julitta Korol
' Indicates the contents of the underlying cells: text, numbers,
' formulas.
'
'
Selection.SpecialCells(xlCellTypeConstants, 2).Select
With Selection.Font
.Name = Arial
.FontStyle = Bold
.Size = 10
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.ColorIndex = 13
End With
Range(B6).Select
Selection.SpecialCells(xlCellTypeConstants, 1).Select
With Selection.Font
.Name = Arial
.FontStyle = Regular
.Size = 10
.Strikethrough = False
procedures. While macros allow you to
mimic keyboard actions, true
procedures can also execute actions
that cannot be performed using the
mouse, keyboard, or menu options. In
other words, procedures are more
complex macros that incorporate
language structures found in the
traditional programming languages.
28. Chapter 1: Introduction to Spreadsheet Automation 11
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.ColorIndex = 11
End With
Range(C6).Select
Selection.SpecialCells(xlCellTypeFormulas, 23).Select
With Selection.Font
.Name = Arial
.FontStyle = Bold
.Size = 10
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.ColorIndex = 3
End With
Range(A1:A3).Select
Selection.EntireRow.Insert
Range(A1).Select
With Selection.Interior
.ColorIndex = 13
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
End With
Range(B1).Select
ActiveCell.FormulaR1C1 = Text
Range(A2).Select
With Selection.Interior
.ColorIndex = 5
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
End With
Range(B2).Select
ActiveCell.FormulaR1C1 = Numbers
Range(A3).Select
With Selection.Interior
.ColorIndex = 3
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
End With
Range(B3).Select
ActiveCell.FormulaR1C1 = Formulas
Range(B4).Select
End Sub
For now, let’s focus on finding answers to two questions: How do you read
the macro code, and how can you edit macros?
29. 12 Chapter 1: Introduction to Spreadsheet Automation
Adding Comments
Take a look at the recorded macro code. Notice the lines that begin with an
apostrophe. These lines indicate comments. By default, comments appear
in green. When the macro code is executed, Visual Basic ignores the com-ment
lines. Comments are often placed within the macro code for
documenting the meaning of certain lines that aren’t obvious. Let’s now add
some comments to the WhatsInACell macro.
1. Activate the Visual Basic Editor window.
2. Click in front of Selection.SpecialCells(xlCellTypeConstants, 2).Select
and press Enter.
3. Move the pointer to the empty line above and add the comment shown
below. Be sure to start with an apostrophe.
' Find and format cells containing text
4. Click in front of Selection.SpecialCells(xlCellTypeConstants, 1).Select
and press Enter.
5. Move the pointer to the empty line above and add the following
comment:
' Find and format cells containing numbers
6. Click in front of Selection.SpecialCells(xlCellTypeFormulas, 23).Select
and press Enter.
7. Move the pointer to the empty line above and add the following
comment:
' Find and format cells containing formulas
8. Click in front of Range(A1:A3).Select and press Enter.
Tip 1-6: About Comments
In the VBE Code window, every line
that begins with an apostrophe is a
comment. The default comment color
is green. You can change the color of
comments in the Options dialog box
(Tools | Options | Editor Format tab).
You can also add a comment at the
end of the line of code. For example,
to add a comment following the line
.ColorIndex = 11, click at the end of
this line, press Tab, enter the apos-trophe,
and then type the text of your
comment. When you are done, the
commented line should look as
follows:
.ColorIndex = 11 ' Sets the font
color to Violet
The comment lines don’t do anything
except provide information to the
user about the purpose of a macro or
macro action. When you write your
own VBA procedures, don’t forget to
include comments. Comments will
make your life easier if you need to
return to the macro procedure sev-eral
months later. They will also allow
others to quickly understand various
parts of your procedure.
30. Chapter 1: Introduction to Spreadsheet Automation 13
9. Move the pointer to the empty line above and add the following
comment:
' Create legend
Analyzing the Macro Code
All macro procedures begin with the keyword Sub and end with the
keywords End Sub. After the Sub keyword comes the actual name of the
macro, followed by a set of parentheses. Between the keywords Sub and
End Sub are statements that Visual Basic executes each time you run your
macro. Visual Basic reads the lines from top to bottom, ignoring the state-ments
preceded with an apostrophe (see the previous section on
comments) and stops when it reaches the keywords End Sub.
Notice that the recorded macro contains many periods. The periods
appear in almost every line of code and are used to join various elements of
the Visual Basic for Applications language. How do you read the instruc-tions
written in this language? They are read from the right side of the last
period to the left. Here are a few statements from the WhatsInACell
procedure:
Range(A1:A3).Select
Select cells A1 to A3.
Selection.EntireRow.Insert
Insert a row in the selected area. Because the previous line of code selects
three cells, Visual Basic will insert three rows.
ActiveCell.FormulaR1C1 = Text
Let the formula of the active cell be “Text.” Because the previous line of
code, Range(B1).Select, selects cell B1, B1 is currently the active cell, and
this is where Visual Basic will enter the text.
With Selection.Interior
.ColorIndex = 3
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
End With
This is a special block of code that is interpreted as follows: Set the color
for the interior of the currently selected cells to red (ColorIndex = 3), set
the interior pattern to solid (xlSolid), and specify the default pattern for the
selected cells (xlAutomatic).
The block of code that starts with the keywords With and ends with the
keywords End With speeds up the execution of the macro code. Instead of
repeating the following instructions each time, the macro recorder uses a
shortcut.
Selection.Interior.ColorIndex = 3
Selection.Interior.Pattern = xlSolid
31. 14 Chapter 1: Introduction to Spreadsheet Automation
Selection.Interior.PatternColorIndex = xlAutomatic
It places the repeating text, Selection.Interior, to the right of the keyword
With and ends the block with the keyword End With.
Cleaning Up the Macro Code
Now, as you review and analyze your macro code line by line, you may
notice that Excel recorded a lot of information that you didn’t intend to
include. For example, after selecting cells containing text, in addition to set-ting
the font style to bold and the color to violet, Excel also recorded the
current state of options on the Font tab—font name, font size, strike-through,
superscript, subscript, shadow, and underline. Take a look at the
following code fragment:
With Selection.Font
.Name = Arial
.FontStyle = Bold
.Size = 10
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.ColorIndex = 13
End With
When you use dialog boxes, Excel always records all the settings. These
additional instructions make your macro code longer and more difficult to
understand. Therefore, when you finish recording your macro, it is a good
idea to go over the recorded statements and delete the unnecessary lines.
1. In the following block of code, delete the lines that are crossed out:
With Selection.Font
.Name = Arial
.FontStyle = Bold
.Size = 10
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.ColorIndex = 13
End With
After the cleanup, only two statements should be left between the
keywords With and End With. These statements are the settings that
you actually changed in the Format dialog box when you recorded this
macro:
32. With Selection.Font
.FontStyle = Bold
.ColorIndex = 13
End With
Chapter 1: Introduction to Spreadsheet Automation 15
2. Locate the macro code that formats cells containing numbers, and make
the necessary changes using the example below:
' Find and format cells containing numbers
With Selection
.SpecialCells(xlCellTypeConstants, 1).Select
.Font.ColorIndex = 11 ' Sets the font color to Violet
End With
Range(C6).Select
3. Locate the macro code that formats cells containing formulas, and make
changes following the example below:
' Find and format cells containing formulas
Selection.SpecialCells(xlCellTypeFormulas, 23).Select
With Selection.Font
.FontStyle = Bold
.ColorIndex = 3
End With
4. Locate the following two lines of code:
Range(A1:A3).Select
Selection.EntireRow.Insert
5. Replace the above two lines of code with the following line:
Range(A1:A3).EntireRow.Insert
Notice that the macro recorder uses the R1C1-style notation to set the for-mula
for the selected cell:
ActiveCell.FormulaR1C1 = Text
ActiveCell.FormulaR1C1 = Numbers
ActiveCell.FormulaR1C1 = Formulas
To select the active cell, the macro recorder uses the word ActiveCell once,
and it applies the word Selection another time. Both of these words are
called properties. You will learn about properties in Chapter 2. When only
one cell is selected, you may use ActiveCell or Selection interchangeably.
Testing the Modified Macro
When you modify the recorded macro, it is quite possible that you may intro-duce
errors. For example, you may delete an important line of code, or you
may inadvertently remove or omit a necessary period. To make sure that
your macro still works correctly after you’re done editing, you must run it.
1. In the Visual Basic Editor Code window, place the cursor in any line of
the WhatsInACell macro code, and choose Run | Run Sub/UserForm.
If you didn’t introduce any problems during the modification of your macro,
the macro will run smoothly and no errors will be reported. To see the
33. 16 Chapter 1: Introduction to Spreadsheet Automation
result of your macro, you must switch to the Microsoft Excel window. To do
this, click the button on the taskbar, or press Alt+F11.
If the Visual Basic Editor encounters an error during the execution of
your macro, you will see a dialog box displaying the type of error found.
Before you run macros, you must make sure that your macro can run in the
worksheet that is currently selected. For example, if you try to run the
WhatsInACell macro when a blank sheet is selected, you will get the “Run
time error ‘1004’—No Cells were found” error message. Click the End but-ton,
and make sure that you select the correct worksheet before you try to
run the macro again.
If the selected worksheet contains only cells with text and you try to
run the WhatsInACell macro, Visual Basic will encounter a problem when
attempting to select cells with numbers. The same “No cells found” mes-sage
will be displayed.
If you omit the period in With Selection.Font on running this line of
code, Visual Basic will generate the “Run time error ‘424’—Object
required” message. Click the Debug button in the message box, and you
will be placed in the Code window. At this time, Visual Basic will enter into
break mode and will use the yellow highlighter to indicate the line that it
had trouble executing. As soon as you correct your error, Visual Basic may
announce “This action will reset your project, proceed anyway?” Click OK
in response to this message. Although you can edit code in break mode,
some edits prevent continuing execution. After correcting the error, run the
macro again, as there may be more errors to be fixed before the macro can
run smoothly. You will find more information on how to handle VBA errors
in Chapters 2 and 13.
Two Levels of Macro Execution
You can run your macros from either the Microsoft Excel window or the
Visual Basic Editor window. When you execute the WhatsInACell macro
from the VBE screen, Visual Basic executes the macro behind the scenes.
You can’t see when Visual Basic selects and applies formatting to the text
cells or when it inserts three empty rows for the color legend. To watch
Visual Basic at work, you must run your macro from the Microsoft Excel
window by choosing Tools | Macro, or arrange your screen in such a way
that both Microsoft Excel and the Visual Basic windows can be viewed at
the same time (see Figure 1-6).
To arrange your screen so that it matches Figure 1-6, perform the fol-lowing
steps:
1. Right-click the empty section of the Windows taskbar. The taskbar is
the bottom area of the screen where the Start button is located.
2. From the Windows shortcut menu, select Tile Windows Vertically.
3. Minimize the windows that are not needed, and repeat step 1 above.
34. Chapter 1: Introduction to Spreadsheet Automation 17
Figure 1-6: If you want to watch the execution of your macro from the level of the Visual
Basic Editor, you must position the Microsoft Excel and VBE windows side by side.
4. Now that both windows are side by side, click anywhere inside the
macro code, and press F5 (or choose Run | Run Sub/UserForm).
Now, sit back and watch. Isn’t it exciting to see Visual Basic quickly
perform the actions you recorded? Later, you will learn how to slow
down Visual Basic so that you can watch the execution of your code
step by step.
Improving Your Macro
After you record your macro, you may realize that the macro can perform
some additional tasks. Adding new instructions to the macro code is not
very difficult if you are already familiar with the Visual Basic language. In
most situations, however, you can do this more efficiently when you dele-gate
the extra tasks to the macro recorder. You may argue that Excel
records more instructions than are necessary. One thing is for sure, how-ever—
the macro recorder does not make mistakes, and you can rely fully
on it.
If you want to add additional instructions to your macro using the
macro recorder, you must record a new macro, then copy the sections you
want, and paste them into the correct location in your original macro.
Let’s add a thick border around cells A1:B3.
35. 18 Chapter 1: Introduction to Spreadsheet Automation
1. Activate the Microsoft Excel window with the worksheet shown in Fig-ure
1-6.
2. Choose Tools | Macro | Record New Macro.
3. In the Macro dialog box, click OK to accept the default macro name and
begin recording.
4. Select cells A1:B3.
5. Choose Format | Cells and click the Border tab.
6. In the Presets section of the dialog box, click the Outline button.
7. Click the thickest line in the Style box and click OK to close the dialog
box.
8. Click cell A1. Notice the thick border around cells A1:B3.
9. Click the Stop Recording button on the Stop Recording toolbar, or
choose Tools | Macro | Stop Recording.
To view the recorded macro, switch to the Visual Basic Editor window. The
macro code that adds a thick border around cells A1:A3 is shown here:
Sub Macro2()
'
' Macro2 Macro
' Macro recorded 5/31/2002 by Julitta Korol
'
'
Range(A1:B3).Select
Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
With Selection.Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.Weight = xlThick
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeTop)
.LineStyle = xlContinuous
.Weight = xlThick
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.Weight = xlThick
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeRight)
.LineStyle = xlContinuous
.Weight = xlThick
.ColorIndex = xlAutomatic
End With
Selection.Borders(xlInsideVertical).LineStyle = xlNone
Selection.Borders(xlInsideHorizontal).LineStyle = xlNone
Range(A1).Select
End Sub
36. Now let’s analyze the recorded code. Do you think you can get rid of some
instructions? Before you go ahead and delete the unnecessary lines of code,
think of how you can use the comment feature. Before you delete any
macro code, comment it out and run the macro with the commented code. If
the Visual Basic Editor does not generate any errors, you can safely delete
the commented lines. If you follow this guideline, you will never find your-self
recording the same keystrokes more than once. And if the macro does
not perform accurately, you can remove the comments from the lines that
may be needed after all. For details on working with comment blocks,
please see Chapter 2.
When you create macros with the macro recorder, you can quickly learn
the VBA equivalents for the Excel menu options and dialog box settings.
Then you can look up the meaning and the usage of these Visual Basic com-mands
in the online help. It’s quite obvious that the more instructions
Visual Basic needs to read, the slower the execution of your macro. Elimi-nating
extraneous commands will speed up your macro. However, to make
your macro code easier to understand, you may want to put on your detec-tive
hat and search for a better way to perform a specific task. For example,
take a look at the code the macro recorder generated for placing a border
around selected cells. It appears that the macro recorder handled each line
separately. It seems hard to believe that Visual Basic does not have a simple
one-line command that places a border around a selection of cells. Learning
the right word or expression in any language takes time. If you look long
enough, you will find that Visual Basic has a BorderAround method that
allows you to add a border to a range of cells and set the Color, LineStyle,
and Weight for the new border.
Using Visual Basic for Applications, the quickest way to create the
thick border around a selection of cells is with the following statement:
Range(A1:B3).BorderAround Weight:=xlThick
The above instruction uses the BorderAround method of the Range object.
It uses the thick line to create a border around cells A1:B3. (The next chap-ter
covers Visual Basic objects, properties, and methods.)
Now let’s add the above instruction to the WhatsInACell macro:
1. Activate the Code window with the WhatsInACell macro.
2. Enter a new line after ActiveCell.FormulaR1C1 = Formulas.
3. In the blank line, enter the following instruction:
Range(A1:B3).BorderAround Weight:=xlThick
4. Place the cursor anywhere in the macro code and press F5 to run the
modified macro.
Chapter 1: Introduction to Spreadsheet Automation 19
37. 20 Chapter 1: Introduction to Spreadsheet Automation
Tip 1-7: Including Additional Instructions
To include additional instructions in
the existing macro, add empty lines
in the required places of the macro
code by pressing Enter and type in
the necessary Visual Basic
statements.
If the additional instructions are key-board
actions or menu commands,
you may use the Macro recorder to
generate the necessary code and
then copy and paste the necessary
lines into the original macro.
Let’s say you would like Visual Basic to notify you when it has finished exe-cuting
the last macro line. This sort of action cannot be recorded, as Excel
does not have a corresponding menu option. However, using the Visual
Basic language, you can add new instructions to your macro by hand.
1. In the Code window, click in front of the End Sub keywords and press
Enter.
2. Place your cursor on the empty line and type the following statement:
MsgBox All actions have been performed.
3. Make sure the cursor is located anywhere in the macro code, and press
F5.
4. When Visual Basic completes the last recorded instruction, it displays
the message. Click OK. You now know for sure that the macro has fin-ished
running.
MsgBox is one of the frequently used VBA functions. You will learn more
about its usage in Chapter 4.
Renaming the Macro
When you add additional actions to your macro, you may want to change its
name to better indicate the purpose of the macro. The name of the proce-dure
should communicate its function as closely as possible. To change the
macro name, you don’t need to press a specific key. In the Code window,
simply delete the old macro name and enter the new name following the
Sub keyword.
Other Methods of Running Macros
So far, you have learned three methods of running macros. You already
know how to run a macro by choosing Tools | Macro | Macros. Unfortu-nately,
this method of running a macro is not convenient if you need to run
your macro often. You also ran the macro in the VBE Code window with the
keyboard shortcut F5 or by choosing Run | Run Sub/UserForm. In addition,
you can run a macro from the Visual Basic Editor window by clicking a but-ton
on the Standard toolbar (Figure 1-7) or choosing Tools | Macro.
38. Chapter 1: Introduction to Spreadsheet Automation 21
Figure 1-7: The Visual Basic procedure can be run from the toolbar button.
Running the Macro Using a Keyboard Shortcut
A popular method to run a macro is by using an assigned keyboard shortcut.
It is much faster to press Ctrl+Shift+D than it is to activate the macro
from the Macro dialog box. Before you use the keyboard shortcut, you must
assign it to your macro.
1. Press Alt+F8 to quickly open the Macro dialog box.
2. In the list of macros, click the name of the WhatsInACell macro, and
then choose the Options button.
3. The Macro Options dialog box appears, as shown in Figure 1-8. The
cursor is located in the Shortcut key text box.
Figure 1-8:
Using the Macro Options dialog box,
you can assign a keyboard shortcut
for running a macro.
4. Hold down the Shift key and press the letter I on the keyboard. Excel
records the keyboard combination as Ctrl+Shift+I.
5. Click OK to close the Macro Options dialog box.
6. Click Cancel to return to the worksheet.
Tip 1-8: Avoid Shortcut Conflicts
If you assign to your macro a keyboard shortcut that conflicts with
the Microsoft Excel built-in shortcut, Excel will run your macro if the
workbook containing the macro code is currently open.
To run your macro using the newly assigned keyboard shortcut, make sure
the Microsoft Excel window is active and press Ctrl+Shift+I.
39. 22 Chapter 1: Introduction to Spreadsheet Automation
Running the Macro from a Menu
If you’d rather work with the menus, you can add your macro as a menu
option. Using the Customize dialog box, you can quickly add your own
menu command to any of Excel’s built-in menus.
1. In the Microsoft Excel window, right-click the empty area of the menu
bar and select Customize from the shortcut menu.
2. In the Customize dialog box, click the Commands tab.
3. In the Categories list box, select Macros.
Figure 1-9:
Creating a custom menu item
(Step 1)
4. Drag Custom Menu Item to the Tools menu. As the menu opens up,
drop the button image to the position where you want to place it. Fig-ure
1-10 shows the custom command placed as the last option on the
Tools menu.
5. To change the name of the custom menu item, right-click the menu
item and edit the text in the Name item on the shortcut menu (Figure
1-11). For this example, change the name to Contents of Cells.
The ampersand () character is used to indicate a keyboard shortcut.
Place the ampersand immediately before the letter you want to be
underlined. If you named the custom option Contents of Cells, the
custom menu option will be displayed as Contents of Cells. Notice that
menu options can contain spaces between the words.
6. To assign a macro to the Contents of Cells menu option, select the last
option—Assign Macro—on the shortcut menu (Figure 1-11). In the
Macro dialog box, select the WhatsInACell macro and click OK. Click
Close to close the Customize dialog box.
40. Chapter 1: Introduction to Spreadsheet Automation 23
Figure 1-10: Creating a custom menu item (Step 2). You can place the custom option in
any Excel menu or submenu.
Figure 1-11: Creating a custom menu item (Step 3). Using the shortcut menu, you can
rename the menu option and assign your own macro to it. To use this shortcut menu, you
must first open the Customize dialog box.
Your macro can now run from your custom menu option. If you close
the shortcut menu before assigning a macro to the menu option, Excel
will prompt you for the macro name when you attempt to use your
menu option for the first time.
41. 24 Chapter 1: Introduction to Spreadsheet Automation
7. Choose Tools | Contents of Cells to run your macro, or press Alt+T
and the letter l.
If you removed a built-in menu or menu option while performing the above
steps, open the Customize dialog box, click the Toolbars tab, and choose the
Reset button. While this will bring back Microsoft Excel default options,
your custom menu option will be removed.
Running the Macro from a Toolbar Button
If you like to use toolbar buttons, you can easily add a custom button to any
toolbar and assign it to your own macro. Let’s add the WhatsInACell macro
to a toolbar.
1. Choose Tools | Customize.
2. In the Customize dialog box, click the Commands tab.
3. In the Categories list box, select Macros.
4. Drag the Custom Button image to the position on the toolbar where
you want to place the button. In this example, the button is added to
the Standard toolbar to the right of the Format Painter button.
5. To change the tooltip of the button, right-click the button and edit the
text in the Name item on the shortcut menu. For this example, change
the name of the button’s tooltip to Contents of Cells.
6. To change the image on the button, right-click the button and select the
Change Button Image command from the shortcut menu. Forty-two
predesigned images included with Excel will appear. Select the image
you want. For this example, the default custom image was replaced
with the pencil image.
7. To assign the macro to the button, right-click the button to open the
shortcut menu and choose the Assign Macro command.
8. Select the WhatsInACell macro and choose OK.
9. Click the Close button to close the Customize dialog box.
10. Point the mouse to the custom button you just created. The Contents
of Cells tooltip appears next to the button (Figure 1-12). Make sure the
active sheet contains a spreadsheet with text, numbers, and formulas.
Then click the custom button to run the macro.
Figure 1-12: You can add a custom button to any toolbar to run your macro.
42. Chapter 1: Introduction to Spreadsheet Automation 25
Running the Macro from a Worksheet Button
Later in this book, you will learn how buttons placed in a worksheet can
help beginning Excel users with data entry. For now, let’s go over the steps
that will attach the WhatsInACell macro to a worksheet button.
1. Activate the example worksheet containing the data.
2. Choose View | Toolbars and select Forms. The Forms toolbar
appears, as shown in Figure 1-13.
3. On the Forms toolbar, click Button.
4. Click anywhere in the worksheet.
5. When the Assign Macro dialog box appears, choose the name of the
macro (WhatsInACell) and click OK.
6. To change the name of Button 1, make sure the button is selected, and
enter the name Contents of Cells. When the button is selected, it
looks like the one shown in Figure 1-13. If the selection handles are not
displayed, right-click Button 1 on the worksheet and choose Edit Text
on the shortcut menu. Select the default text and enter the new name.
7. When you’re done renaming the button, click anywhere in the
worksheet and outside the button to exit the Edit mode.
8. To run your macro, click the button you just created.
Figure 1-13: You can attach your macro to a button placed in a worksheet.
43. 26 Chapter 1: Introduction to Spreadsheet Automation
Tip 1-9: Adding Controls to a Worksheet
You can add controls to a worksheet
using the Forms toolbar (see Figure
1-13) or the Control Toolbox (see
Figure 1-14). Both toolbars can be
accessed from the View menu by
selecting the Toolbars option.
Controls accessed via the Forms
toolbar are compatible with earlier
versions of Excel (5.0, 7, and 97)
and can be used on chart sheets,
old XLM macro sheets, and
worksheets when all you want to do
is run a macro by clicking a control.
The controls in the Control Toolbox
are known as ActiveX controls. You
can place the ActiveX controls on
Saving Macros
Figure 1-14:
Default tools in the Control
Toolbox
worksheets or your custom forms
that you create by using the Visual
Basic Editor. While the controls
located on the Forms toolbar can
only respond to the Click event, the
ActiveX controls have many different
actions, or events, that can occur
when you use the control.
When you use a control from the
Forms toolbar, you assign a macro
to it that is stored in a module of This
Workbook, New Workbook, or Per-sonal
Macro Workbook. When you
use an ActiveX control, write macro
code that is stored with the control
itself.
The WhatsInACell macro you created in this chapter is located in a
Microsoft Excel workbook. To save the macro on a disk, you need to save
the open workbook. I suggest that you save your macro now in a workbook
file named Chap01.xls. After you save the workbook, close it and then open
a brand new workbook. Notice that your custom toolbar button is still avail-able,
as is the Contents of Cells option on the Tools menu. Before you try to
run your macro using any of these tools, enter the text “Addition” in cell
A1, the number 2 in cell A2, the number 4 in cell A3, and =Sum(A2:A3) in
cell A4. When you run the macro, Excel opens the appropriate workbook
file and executes the procedure assigned to your custom tool.
44. Printing Macros
Chapter 1: Introduction to Spreadsheet Automation 27
If you want to document your macro or perhaps study the macro code when
you are away from the computer, you can print your macros. You can print
the entire module sheet where your macro is stored or indicate a selection
of lines to print.
To print the entire module sheet that contains your macro:
1. Place the cursor anywhere in the module sheet.
2. Choose File | Print.
3. In the Print—VBA Project dialog box, the Current Module option but-ton
should be selected.
4. Click OK to print the module sheet.
To print selected text:
1. In the module sheet, highlight the text you want to print.
2. Choose File | Print.
3. In the Print—VBA Project dialog box, the Selection option button
should be selected.
4. Click OK to print the highlighted text.
Storing Macros in the Personal Macro Workbook
When you record a macro, you can specify storing the macro code in the
Personal Macro Workbook. When you store a macro in the Personal Macro
Workbook, Excel creates a file named Personal.xls and places it in the
XLStart folder, which is a subdirectory of Program FilesMicrosoft
OfficeOffice. Files that were saved to the XLStart folder are loaded auto-matically
each time you start Excel. The Personal Macro Workbook is a
convenient place to store general-purpose macros like the following one.
You will now record a general-purpose macro called FormulasOnOff. The
purpose of this macro is to toggle the display of worksheet formulas on and
off.
1. Choose Tools | Macro | Record New Macro.
2. In the Record Macro dialog box, enter FormulasOnOff in the Macro
name box.
3. Choose Personal Macro Workbook from the Store macro in drop-down
list.
4. Click in the Shortcut key text box, and press Shift+F.
5. Choose OK to exit the Record Macro dialog box.
6. Press Ctrl+~ (tilde character) to turn on the display of formulas, or
choose Tools | Options and click the Formulas check box on the
View tab in the Windows options area. When you turn on the display of
formulas, the worksheet cells show the formulas instead of the values
45. 28 Chapter 1: Introduction to Spreadsheet Automation
that the formulas produce. If you are recording this macro on a blank
sheet, the only thing you’ll notice is a change in the width of the
worksheet columns.
7. Click the Stop Recording button on the Stop Recording toolbar, or
choose Tools | Macro | Stop Recording.
8. To see the macro code, press Alt+F11 or choose Tools | Macro |
Visual Basic Editor.
In the Visual Basic Editor screen, the Project Explorer window now shows an
additional VBA project (Personal.xls). To open the project, click the plus sign
(+) to the left of the project name. The VBA project contains two folders:
Microsoft Excel Objects and Modules. Click the plus sign next to the Mod-ules
folder to open it and then double-click Module1. The Code window
shows the contents of the FormulasOnOff macro (Figure 1-15). Each Excel
workbook contains a single project. The first time you record a macro, Excel
creates a module folder and places your macro code in Module1. If you record
another macro in the same workbook, Excel places it below the previously
recorded macro in the same Module1 sheet. All macros recorded in the same
work session are stored in the same module. If you close Excel, reopen the
same workbook and record a new macro, Excel will store it in a new module.
Figure 1-15: In the Project Explorer window you can select the project you want to
work with.
46. Chapter 1: Introduction to Spreadsheet Automation 29
When you recorded your macro, you turned on the display of formulas. The
macro name suggests that the macro can toggle the formulas on and off. To
make this macro behave exactly this way, you must edit it.
The recorded macro line sets the display of formulas in the active win-dow
to True:
ActiveWindow.DisplayFormulas = True
The False setting will turn off the display of formulas:
ActiveWindow.DisplayFormulas = False
To make a toggle in VBA, you need to connect both statements in the fol-lowing
way:
ActiveWindow.DisplayFormulas = Not ActiveWindow.DisplayFormulas
Replace the recorded macro line with the statement above and run the
macro. No matter how many times you play this macro, it always knows
what to do. You can use the same idea to create macros that toggle the dis-play
of gridlines or other Microsoft Excel features on and off.
When you close Microsoft Excel, you will be prompted to save the
changes you made to the Personal Macro Workbook. Click OK to save the
changes. When you restart Excel, the Personal Macro Workbook will auto-matically
load in the background.
If you want to store other macros in the Personal Macro Workbook, you
can take one of the following routes:
Record a new macro and choose the Personal Macro Workbook for its
storage location.
Switch to the Visual Basic Editor and open the project that contains the
macro you want to move to the Personal Macro Workbook. Cut the
macro code from the current location and open the Personal Macro
Workbook project. Paste the macro code into the existing module, or
create a new module prior to pasting.
Choose File | Import File… to bring the macro code from a text file or
another Visual Basic project file (*.frm, *.bas, *.cls).
Opening Workbooks Containing Macros
Whenever you open a workbook that contains macros, Excel displays a
warning message, as shown in Figure 1-16. To prevent Excel from display-ing
this message, you can turn off the virus protection using the Security
dialog box (Figure 1-17).
When the virus message comes up, you can select:
Disable Macros—Click this button if you are opening a workbook
from an unfamiliar source, such as an Internet site or an e-mail, and you
want to protect your computer from any macro viruses that may be in
the workbook. The workbook will be opened without running any
47. 30 Chapter 1: Introduction to Spreadsheet Automation
auto-macros it may contain. You will then be able to switch to the
Visual Basic Editor and review the macros if they are not password
protected. After checking the macros, you can close the workbook and
then reopen it with macros enabled.
Enable Macros—If you know that the workbook comes from a trusted
source and contains useful macros, click the Enable Macros button.
More Info—Click this button if you need more information before you
decide whether to open the workbook with the macros enabled or
disabled.
Microsoft Excel 2002 has a useful feature that allows you to
automatically disable all macros that are not signed and sent from a
trusted source. To access this feature, choose Tools | Macro | Security.
When you create macros that you want to distribute to others, you can use
the Digital Signature feature available in the Visual Basic Editor’s Tools
menu to confirm that the macro does not introduce a virus.
A digital signature on a macro is similar to a handwritten signature on a
printed letter. Search the Microsoft Excel online help for information on
how to install and create your own digital signature. To access related top-ics,
type “digital signature” in the Answer Wizard.
Figure 1-16:
If the virus protection is turned
on, Excel displays a warning
message when the workbook
contains macros.
Figure 1-17:
Selecting the Medium option button
will allow you to choose whether to
run or not to run macros upon
opening a workbook.
48. Chapter 1: Introduction to Spreadsheet Automation 31
The Visual Basic Editor Window
Now that you know how to record, run, and edit macros, let’s spend some
time in the Visual Basic Editor window and become familiar with some of
its features.
With the tools located in the Visual Basic Editor window, you can:
Write your own VBA procedures
Create custom forms
View and modify object properties
Test VBA procedures and locate errors
The Visual Basic Editor window can be accessed in two ways:
From the Tools menu in the Microsoft Excel application window:
Choose Tools | Macro | Visual Basic Editor.
From the keyboard: Press Alt+F11.
Understanding the Project Explorer Window
The Project Explorer window displays a hierarchical list of currently open
projects and its elements.
The VBA project can contain the following elements:
Worksheets
Charts
This Workbook—the workbook where the project is stored
Modules
Classes—special modules that allow you to create your own objects
Forms
References to other projects
With the Project Explorer you can manage your projects and easily move
between projects that are currently loaded into memory.
You can activate the Project Explorer window in one of three ways:
From the View menu by selecting Project Explorer
From the keyboard by pressing Ctrl+R
From the toolbar by clicking the Project Explorer button (see Figure
1-18)
The Project Explorer window contains three buttons.
The first button from the left (View Code) displays the Code window
for the selected module. The middle button (View Object) displays the
selected sheet in the Microsoft Excel Object folder or a form located in the
Forms folder. The first button from the right (Toggle Folders) hides and
unhides the display of folders in the Project Explorer window.
49. 32 Chapter 1: Introduction to Spreadsheet Automation
Figure 1-18: Buttons on the Standard toolbar provide a quick way to access many
Visual Basic features.
Understanding the Properties Window
The Properties window allows you to review and set properties of various
objects in your project. The name of the currently selected object is dis-played
in the Object box located just below the Properties window’s title
bar. Properties of the object can be viewed alphabetically or by category by
clicking on the appropriate tab (Figure 1-19).
Alphabetic Tab—Alphabetically lists all properties for the selected
object. You can change the property setting by selecting the property
name and typing or selecting the new setting.
Categorized Tab—Lists all properties for the selected object by
category. You can collapse the list so that you see the categories, or you
can expand a category to see the properties. The plus (+) icon to the
left of the category name indicates that the category list can be
expanded. The minus (–) indicates that the category is currently
expanded.
The Properties window can be accessed in three ways:
From the View menu by selecting Properties Window
From the keyboard by pressing F4
From the toolbar by clicking the Properties Window button (see Figure
1-18)
50. Chapter 1: Introduction to Spreadsheet Automation 33
Figure 1-19: The Properties window displays the current settings for the
selected object.
Understanding the Code Window
The Code window is used for Visual Basic programming as well as for view-ing
and modifying the code of recorded macros and existing VBA
procedures. Each module can be opened in a separate code window.
There are several ways to activate the Code window:
From the Project Explorer window, choose the appropriate UserForm
or module. Then click the View Code button.
From the menu, choose View | Code.
From the keyboard, press F7.
At the top of the Code window, there are two drop-down list boxes (Figure
1-20) that allow you to move quickly within the Visual Basic code. In the
Object box on the left side of the Code window, you can select the object
whose code you want to view. The box on the right side of the Code window
lets you quickly choose a particular procedure or event procedure to view.
When you open this box, the names of all procedures located in a module
are sorted alphabetically. If you select a procedure in the Procedures/Events
box, the cursor will jump to the first line of this procedure.
By dragging the split bar (Figure 1-20) down to a selected position in
the Code window, you can divide the Code window into two panes (Figure
1-21). You can then view different sections of a long procedure or a different
51. 34 Chapter 1: Introduction to Spreadsheet Automation
Figure 1-20: The Visual Basic Code window has several elements that make it easy to locate
procedures and review the VBA code.
procedure in each pane. Setting up the Code window for the two-pane dis-play
is often used for copying or cutting and pasting sections of code
between procedures of the same module. To return to the one-window dis-play,
simply drag the split line all the way to the top of the Code window.
At the bottom of the Code window, there are two icons. The Procedure
View icon displays only one procedure at a time in the Code window. To
select another procedure, use the Procedures/Events box. The Full Module
View icon displays all the procedures in the selected module. Use the verti-cal
scroll bar to scroll through the module’s code.
The margin indicator bar is used by the Visual Basic Editor to display
helpful indicators during editing and debugging. If you’d like to take a quick
look at some of these indicators, skim through Chapter 13.
52. Chapter 1: Introduction to Spreadsheet Automation 35
Other Windows in the Visual Basic Editor Window
In addition to the Code window, there are other windows that are frequently
used in the Visual Basic environment:
The Form window is used for creating custom dialog boxes and user
forms. You will learn how to do these sorts of things in Chapter 10.
Figure 1-22 displays the list of windows that can be docked in the
Visual Basic Editor window. You will learn how to use some of these win-dows
in Chapter 2 (Object Browser, Immediate window) and others in
Chapter 13 (Locals window, Watches window).
Figure 1-21:
For reviewing longer
procedures, you can divide
the Code window into two
panes.
Figure 1-22:
The Docking tab in the
Options dialog box allows
you to choose which
windows you want to be
dockable.
53. 36 Chapter 1: Introduction to Spreadsheet Automation
What’s Next…
By following along with some spreadsheet automating examples, you
have learned not only how to record a macro but also how to view, read, and
modify the Visual Basic code. In addition, you tried various methods of run-ning
macros. You ended the chapter with a quick tour of the Visual Basic
Editor window. The next chapter introduces you to the fundamentals of
Visual Basic for Applications. You will learn many new terms and, most
importantly, you will acquire a useful VBA vocabulary that will let you dele-gate
even more tasks to Excel.
54. Chapter 2
First Steps in
Visual Basic for
Applications
Understanding Instructions, Modules, and Procedures
Assigning a Name to the VBA Project Renaming the Module
Calling a Procedure from Another Project Understanding
Objects, Properties, and Methods Learning about Objects,
Properties, and Methods Syntax Versus Grammar Breaking
Up Long VBA Statements Understanding VBA Errors In
Search of Help On-the-fly Syntax and Programming Assistance
Using the Object Browser Using the VBA Object Library
Locating Procedures with the Object Browser Using the Imme-diate
Window Obtaining Information in the Immediate Window
Learning about Objects Doing Things with Spreadsheet Cells
Using the Range Property Using the Cells Property Using
the Offset Property Other Methods of Selecting Cells
Selecting Rows and Columns Obtaining Information about the
Worksheet Entering Data in a Worksheet Returning Informa-tion
Entered in a Worksheet Finding Out about Cell Formatting
Moving, Copying, and Deleting Cells Doing Things with
Workbooks and Worksheets Doing Things with Windows
Managing the Excel Application What’s Next…
37