Beruflich Dokumente
Kultur Dokumente
Introduction to
Spreadsheet
Automation
Are you ready to build intelligence into your Microsoft Excel 2002 spreadsheets? 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 havea 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 Excels 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.
worksheets, as well as combine different formats, such as fonts, colors, borders, 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 formatting 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. Dont leave anything out. Like a voice recorder, Microsoft
Excels 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 its 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 formatted with distinct font colors and styles to help identify the contents of
the underlying cells.
Figure 1-1:
Finding out whats 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.
2.
3.
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.
6.
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.
9.
Recording a Macro
Now that you know what actions you need to perform, its 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 | Formats. 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.
2.
Choose Tools | Macro | Record New Macro. The Record Macro dialog 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.
4.
5.
6.
Enter the following text in the Description box: Indicates the contents of the underlying cells: text, numbers, formulas.
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.
Relative Reference
Stop Recording
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.
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.
2.
3.
Click the name of the macro you want to run (see Figure 1-4).
4.
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. Dont panic. Excel makes it
possible to modify the macro without forcing you to go through the tedious
process of recording your keystrokes again.
Figure 1-4:
In the Macro dialog box you
can select a macro to run,
edit, or delete.
1.
2.
3.
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.
Dont 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 windows that are docked in the Visual Basic Editor window: the Project
10
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
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, lets focus on finding answers to two questions: How do you read
the macro code, and how can you edit macros?
12
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 comment lines. Comments are often placed within the macro code for
documenting the meaning of certain lines that arent obvious. Lets now add
some comments to the WhatsInACell macro.
1.
2.
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.
5.
Move the pointer to the empty line above and add the following
comment:
' Find and format cells containing numbers
6.
7.
Move the pointer to the empty line above and add the following
comment:
' Find and format cells containing formulas
8.
9.
13
Move the pointer to the empty line above and add the following
comment:
' Create legend
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
14
Selection.Interior.PatternColorIndex = xlAutomatic
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:
15
With Selection.Font
.FontStyle = "Bold"
.ColorIndex = 13
End With
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.
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 formula 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.
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 didnt introduce any problems during the modification of your macro,
the macro will run smoothly and no errors will be reported. To see the
16
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 1004No Cells were found error message. Click the End button, 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 message 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 424Object
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.
2.
3.
Minimize the windows that are not needed, and repeat step 1 above.
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. Isnt 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.
18
1.
2.
3.
4.
5.
6.
7.
8.
9.
Activate the Microsoft Excel window with the worksheet shown in Figure 1-6.
Choose Tools | Macro | Record New Macro.
In the Macro dialog box, click OK to accept the default macro name and
begin recording.
Select cells A1:B3.
Choose Format | Cells and click the Border tab.
In the Presets section of the dialog box, click the Outline button.
Click the thickest line in the Style box and click OK to close the dialog
box.
Click cell A1. Notice the thick border around cells A1:B3.
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
19
Now lets 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 yourself 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 commands in the online help. Its quite obvious that the more instructions
Visual Basic needs to read, the slower the execution of your macro. Eliminating extraneous commands will speed up your macro. However, to make
your macro code easier to understand, you may want to put on your detective 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 chapter covers Visual Basic objects, properties, and methods.)
Now lets add the above instruction to the WhatsInACell macro:
1.
2.
3.
4.
Place the cursor anywhere in the macro code and press F5 to run the
modified macro.
20
Lets say you would like Visual Basic to notify you when it has finished executing 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:
3.
Make sure the cursor is located anywhere in the macro code, and press
F5.
4.
MsgBox is one of the frequently used VBA functions. You will learn more
about its usage in Chapter 4.
21
Figure 1-7: The Visual Basic procedure can be run from the toolbar button.
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.
6.
To run your macro using the newly assigned keyboard shortcut, make sure
the Microsoft Excel window is active and press Ctrl+Shift+I.
22
In the Microsoft Excel window, right-click the empty area of the menu
bar and select Customize from the shortcut menu.
2.
3.
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. Figure 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 Ce&lls.
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 Ce&lls, 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
optionAssign Macroon 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.
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.
24
7.
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. Lets 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 buttons tooltip to Contents of Ce&lls.
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.
25
2.
3.
4.
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.
8.
Figure 1-13: You can attach your macro to a button placed in a worksheet.
26
Figure 1-14:
Default tools in the Control
Toolbox
Saving Macros
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 available, 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.
27
Printing Macros
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.
2.
3.
In the PrintVBA Project dialog box, the Current Module option button should be selected.
4.
2.
3.
4.
2.
3.
Choose Personal Macro Workbook from the Store macro in dropdown list.
4.
5.
6.
28
that the formulas produce. If you are recording this macro on a blank
sheet, the only thing youll notice is a change in the width of the
worksheet columns.
7.
8.
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 Modules 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.
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 window to True:
ActiveWindow.DisplayFormulas = True
To make a toggle in VBA, you need to connect both statements in the following 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 display 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 automatically load in the background.
If you want to store other macros in the Personal Macro Workbook, you
can take one of the following routes:
n
Record a new macro and choose the Personal Macro Workbook for its
storage location.
n
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.
n
Choose File | Import File to bring the macro code from a text file or
another Visual Basic project file (*.frm, *.bas, *.cls).
30
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.
When you create macros that you want to distribute to others, you can use
the Digital Signature feature available in the Visual Basic Editors 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 topics, type digital signature in the Answer Wizard.
31
32
Figure 1-18: Buttons on the Standard toolbar provide a quick way to access many
Visual Basic features.
33
Figure 1-19: The Properties window displays the current settings for the
selected object.
34
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 display is often used for copying or cutting and pasting sections of code
between procedures of the same module. To return to the one-window display, 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 vertical scroll bar to scroll through the modules code.
The margin indicator bar is used by the Visual Basic Editor to display
helpful indicators during editing and debugging. If youd like to take a quick
look at some of these indicators, skim through Chapter 13.
35
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.
36
Whats 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 running 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 delegate even more tasks to Excel.