Sie sind auf Seite 1von 31

Microsoft Excel 2007

Automation
Through
Macros

DASH DESIGNS CONSULTING


Technology Training and Consulting Services

MODU LE

Microsoft Excel 2007 - Automation Through Macros For The Haas School, UC Berkeley Dash Designs Consulting

Microsoft Excel 2007


Automation Through Macros
For
The Haas School of Business,
University of California
Revised: November 4, 2007

Copyrights and Trademarks

2007, Dash Designs Consulting, Jerry Maletsky


San Rafael, CA 94903
email: jerry@dashdesignsconsulting.com
web site: www.dashdesignsconsulting.com
fax (415) 491-1490

Dash Designs Consulting gives permission to the Haas School of


Business of the University of California at Berkeley to reprint this
training manual for internal use only. No re-sale of this material or
renunciation of copyrights are granted by this author.

Any mention or use of Microsoft, University of California, or any


third party products is hereby acknowledged by Dash Designs
Consulting to be for the sole purpose of editorial and educational
use of this training manual and for the benefit of the mentioned

Microsoft Excel 2007 - Automation Through Macros For The Haas School, UC Berkeley Dash Designs Consulting

Excel 2007
Automation Through Macros
Table of Contents
Planning and Recording Macros ... 4
Making Macros Flexible .............. 16
Reference Workbook: Macros Workbook.xlsx

Microsoft Excel 2007 - Automation Through Macros For The Haas School, UC Berkeley Dash Designs Consulting

Microsoft Excel 2007

CHAPTER

Automation
Through
Macros

Jerry Maletsky
Dash Designs Consulting
Technology Training and Consulting

Microsoft Excel 2007 - Automation Through Macros - Dash Designs Consulting

CHAPTER

Planning and Recording Macros

WHY RECORD A MACRO?


Many tasks that you perform in Microsoft Excel are often repetitive.
These can
include formatting cells, entering worksheet labels, printing commands, or deleting
data. Individual tasks can be completed quickly. When there are several repetitive
tasks that need to be executed at the same time, a macro can accomplish those
tasks very efficiently.
Macros are Microsoft Office objects that record these tasks as you do them once.
Then they can be executed within an Excel worksheet to play back those recorded
tasks at any time in the future.
When you record a macro, Microsoft Excel stores each tasks steps in a
programming language called Visual Basic (actually Visual Basic for Applications or
VBA). This programming language can be examined and edited to further
customize a macro.
The main limitation of a macro is that it will always execute the same steps exactly
as they were recorded. That is, if in recording the macro, one of the steps is to
open a workbook named Budget.xls, then that is the same file it will open each time
that macro is run. In order to make macros more flexible some editing of the VBA
code is required.
Macros offer these advantages

Save time

Streamline repetitive tasks

Create consistent formatting techniques

Create custom commands and toolbar buttons

Safeguard data changes

Microsoft Excel 2007 - Automation Through Macros - Dash Designs Consulting

CHAPTER

Planning and Recording Macros

EXCEL 2007 MACRO SECURITY


Excel 2007 requires that any workbook containing macros needs to be saved as a
Macro-Enabled workbook (see previous page). This is a new type of workbook
(with an .xlsm extension) in Office 2007. This can be accomplished by using the
Save As command in the Office Button. Although the user can still save the file
as a normal workbook, any macros contained within that workbook would be lost.
When the macro-enabled workbook is opened, initially, the macros contained within
that workbook will be disabled. However, the user can click the options button in
the Security Warning bar (see below) and enable those macros.

Microsoft Office Button

For more information on


Macro Security see Microsoft Excel Help System.

Microsoft Excel 2007 - Automation Through Macros - Dash Designs Consulting

CHAPTER

Planning and Recording Macros

1
SETTING MACRO SECURITY

Microsoft Office takes precautions before opening files that contain macros. That is because viruses can be contained within macros. Antivirus software that is installed with
Microsoft Windows, and kept updated, scans files for known viruses before they are
opened. In addition, Microsoft Office contains Macro Setting Security options that help
protect files with macros from being opened inadvertently without the users knowledge
that they contain macros.
Within Microsoft Excels Trust Center command are the Macro Settings options. This
settings dialog box has several options that range from disabling macros automatically before a file can be opened to opening any file regardless whether or not they contain macros.
Security settings can be viewed in Microsoft Excel through the, OFFICE BUTTON,
EXCEL OPTIONS BUTTON, TRUST CENTER, MACRO SETTINGS command.

Steps:
Click Microsoft Office Button
Click the Excel Options button
Click the Trust Center category (left panel)
Click Trust Center Settings... button (right panel)
Click Macro Settings category (left panel)

Microsoft Excel 2007 - Automation Through Macros - Dash Designs Consulting

CHAPTER

Planning and Recording Macros

SETTING MACRO SECURITY


Trust Center Dialog Box

Macro Settings Dialog Box

Microsoft Excel 2007 - Automation Through Macros - Dash Designs Consulting

Planning and Recording Macros

CHAPTER

1
RECORDING A MACRO

Macros are recorded much like recording a television show. After the recorder is activated
it memorizes every step taken to complete the required tasks.
Before recording a macro, it is a very good idea to practice and try out the steps needed to
be recorded. That way, it is less likely that steps will be missed as well as ensuring that
the steps all work.
In order to record a macro, the user needs to open the Record Macro dialog box. There
will be several options necessary to set before the macro recording begins. These include
the macro name, a shortcut key to play it back, and the location in which to store the
macro.
The following defines the options available

MACRO NAME:

The first character of the macro name must be a letter. Other characters can be
letters, numbers, or underscore characters.

Spaces are not allowed in a macro name; an underscore character works well as
a word separator.

Do not use a macro name that is also a cell reference or you can get an error
message that the macro name is not valid.

SHORTCUT KEY: (Optional)

In order to avoid overwriting global shortcut keys such as Ctrl+C (Copy) or


Ctrl+V (Paste) use the Shift key and the letter that will be used to execute the
macro later.

The shortcut key letter you use cannot be a number or special character such as
@ or #.

The macro can also be executed from the Macro dialog box, a toolbar button, or
even a menu command.

STORE MACRO IN:

This Workbook ( macro can only be run in the workbook it is being recorded in
or when that workbook is opened)

Personal Macro Workbook

New Workbook (macro is stored in a separate workbook that must be opened


in order to run it)

DESCRIPTION: (Optional)

(global macro can run in any workbook)

Enter a summary description that will help recall what tasks the macro performs.
Microsoft Excel 2007 - Automation Through Macros - Dash Designs Consulting

CHAPTER

Planning and Recording Macros

RECORDING A MACRO
View Tab: Macros: Record New Macro Dialog Box

Steps:
View Tab: Macro: Record Macro command
Type a name for the macro
(no spaces use an underscore if necessary)

Give it a shortcut key (optional) Use Shift key + Letter so you dont
overwrite the regular command shortcut keys

Designate a storage area


Type a description
Click OK
Set the recording mode to relative or absolute
(see next page)

Perform the necessary tasks


Click the Stop Recorder command when completed
Great Tip!

Note: Once you click OK in the Record Macro dialog box the macro begins
recording every step you perform. Dont worry about small mistakes. The
macro plays back so quickly that you probably wont even notice them. The
macro can be edited afterwards (VBA) or re-recorded.
Microsoft Excel 2007 - Automation Through Macros - Dash Designs Consulting

CHAPTER

Planning and Recording Macros

1
RECORDING ABSOLUTELY

OR

RELATIVELY

When you create a macro Microsoft Excel records those steps either in
Absolute Reference mode or Relative Reference mode. The mode in which
the macro is recorded may depend on the tasks and the steps that need to be executed in order to successfully execute.
When a macro is recorded in Absolute Reference mode any cell you select or
navigate to will be recorded as just that cell address (i.e. selecting cell B10 will be
recorded as selecting cell B10).
When a macro is recorded in Relative Reference mode any cell you select or navigate to will be recorded as that cell address relative to the cell previously selected.
For example, if the active cell is A5 and the next cell selected is B10, in Relative
Reference mode Excel will record that as moving to the cell 1 column to the right
and 5 rows down.
Some macros will execute more efficiently in Absolute Reference mode while others will be more effective in Relative Reference mode.
Excel will continue to record macros with relative references until you quit Excel or
until you click Relative Reference again, so that it is not selected.

Microsoft Excel 2007 - Automation Through Macros - Dash Designs Consulting

RECORDING ABSOLUTELY

OR

CHAPTER

Planning and Recording Macros

RELATIVELY

View Tab: Macros Command

Use Relative References Command


Command is On - Relative Reference
Command is Off - Absolute Reference

Steps:
After clicking OK to start the recorder...
Set the recording mode to relative or absolute
Perform the necessary tasks
Click the Stop Recording command when completed

Microsoft Excel 2007 - Automation Through Macros - Dash Designs Consulting

CHAPTER

Planning and Recording Macros

EXECUTING A MACRO
Once a macro has been recorded, it can be played back when needed. There are
several methods that can be used to execute the macro. It can be played back using the Macros dialog box, pressing the shortcut key combination (i.e.
Ctrl+Shift+H), or clicking on a toolbar button or menu command that it has been
assigned.

View Tab: Macros Command

10

Microsoft Excel 2007 - Automation Through Macros - Dash Designs Consulting

CHAPTER

Planning and Recording Macros

VIEWING THE CODE


Once the macro is finished recording the code that Microsoft Excel creates
to perform those necessary tasks are available in the VBA window. The
VBA code can be viewed by clicking the View tab: Macros button: View
Macros command, selecting the preferred macro, then clicking the Edit
button to access the code.
Having access to the VBA code allows you to edit and customize the
macro. Much of the code recorded in a macro is reflective of the step performed (i.e. Range (B10).Select ). More complex steps have to be written in VBA and requires additional training.
Note that the macro starts with Sub Macroname and ends with End Sub.

Microsoft Excel 2007 - Automation Through Macros - Dash Designs Consulting

11

CHAPTER

Planning and Recording Macros

1
EDITING VBA CODE

Occasionally after recording a macro, you might find that some steps were omitted,
some labels were mistyped, some formatting options need to changed. Although
the macro can be re-recorded, it might be more efficient to just edit the necessary
changes in the VBA code. You do not have to be an expert at VBA in order to do
this. Many of the recorded steps are reflective of the task that you might have performed with your mouse.
In addition, omitted steps can be recorded separately and then copied and pasted
into the original macro code.

Note: in the above example the company name


ABC Company can be edited and changed
without changing the macro. The quotes are
important and must be left.

Steps:
Click View Tab: Macros button: View Macros command
In the Macros dialog box, select the preferred macro
Click Edit button
Edit the macro as needed
Close the VBA window
When the workbook is saved the macro will be updated

12

Microsoft Excel 2007 - Automation Through Macros - Dash Designs Consulting

CHAPTER

Planning and Recording Macros

EDITING THE PERSONAL MACRO WORKBOOK


The Personal Macro Workbook (Personal.xlsb) is a special workbook in which
macros can be stored (see page 6 - Recording A Macro). A macro stored in the
Personal Macro Workbook is available to run in any workbook opened on your
computer in Microsoft Excel. A macro stored in This Workbook is only available
to run when that workbook is opened but can run on any computer that opens that
workbook. The Personal Macro Workbook is an empty workbook created by Excel
when macros are stored in it. It is automatically hidden when Excel starts.
When editing macros stored in the Personal Macro Workbook the user must first use
the View tab: UnHide command to make that workbook visible. Otherwise, Microsoft Excel will not allow that macro to be edited.

Dont forget to hide (View Tab: Hide)


the Personal.xlsb file when editing the
macros is completed. Otherwise, you
might add data to that workbook
inadvertently.

Personal.xlsb workbook

Microsoft Excel 2007 - Automation Through Macros - Dash Designs Consulting

13

CHAPTER

Planning and Recording Macros

1
ADDING MORE COMMANDS TO A MACRO

Sometimes when a macro is recorded and reviewed, it might be noticed that some
tasks were omitted. Instead of re-recording the entire macro, a new macro can be
recorded with just those steps and then added to the original macro through Copy
and Paste commands.

Steps:
After recording the new macro with the additional steps...

Click View tab: Macros button: View Macros command


In the Macros dialog box, select the new macro
Click Edit button
Select the VBA code to add to the original macro
Click Edit menu: Copy (or any other Copy method)
In the VBA window, position the cursor in the original macro where the
new code is to be placed

Click Edit menu: Paste (or any other Paste method)


Close the VBA window
When the workbook is saved the macro will be updated

14

Microsoft Excel 2007 - Automation Through Macros - Dash Designs Consulting

CHAPTER

Planning and Recording Macros

ADDING MORE COMMANDS TO A MACRO

Original
Macro

Original
Macro and
New Macro

Original
Macro With
Added Com-

Microsoft Excel 2007 - Automation Through Macros - Dash Designs Consulting

15

CHAPTER

Making Macros More Flexible

ADDING INTERACTIVE DIALOG BOXES


Recorded macros execute steps exactly as they are recorded. That is, if in
recording a macro, the file Budget.xls is opened that is the same file that
will be opened each time that macro is executed. However, you may prefer
to open different files each time the macro is executed.
With an Input box, Excel can prompt for the name of the file or perhaps
the cell(s) to select, or data to enter. An InputBox is a Visual Basic function that is added to the recorded macro. The InputBox is assigned a name
and that name is attached to the routine it helps execute. When the data
is entered into the InputBox (i.e., file name, cell address, data) that variable
is used to complete that routine.
The syntax for the InputBox consists of the following:
Name=InputBox(prompt,title,default,xpos,ypos,helpfile,context)

Argument

16

Required/Optional

Prompt

Required!

Title

Optional

Default

Optional

Xpos

Optional

Ypos

Optional

Helpfile

Optional

Context

Required
(if Helpfile argument is
used)

Description
Text that will appear as the message in
the Input box (up to 1,024 characters).
Must be entered in double-quotes.
Text that will appear in the Title Bar of
the Input box dialog. Must be entered
in double-quotes.
Specifies entry to be entered by default.
Must be entered in double-quotes.
Specifies the horizontal position from the
left edge of the Input box to the left
edge of the screen.
Specifies the vertical position from the
top edge of the Input box to the top
edge of the screen
Specifies the help file (if created) to display if a Help button (added to the Input
box automatically)
Specifies help context number assigned
by author to the help file.

Microsoft Excel 2007 - Automation Through Macros - Dash Designs Consulting

CHAPTER

Making Macros More Flexible

ADDING INTERACTIVE DIALOG BOXES


Example of InputBox Macro:

Before:
Sub OpenWkbk()
'
' Chicago Macro
' Macro recorded 11/1/2007 by Jerry Maletsky Opens the Macros Workbook
'
' Keyboard Shortcut: Ctrl+Shift+O
'
Workbooks.Open Filename:= _
"C:\Documents and Settings\Jerry Maletsky\My
Documents\Macros.xlsx"
End Sub
After

Sub OpenWkbk()
'
' OpenWkbk Macro
' Macro recorded 7/13/2005 by Jerry Maletsky Opens the Specified Workbook
'
' Keyboard Shortcut: Ctrl+Shift+O
'
OpenBk=InputBox(Enter the name of the workbook to open,Open Workbook)
Workbooks.Open Filename:= (OpenBk)
End Sub

Microsoft Excel 2007 - Automation Through Macros - Dash Designs Consulting

17

CHAPTER

Making Macros More Flexible

2
USING MESSAGE BOXES IN MACROS

Message boxes can display information to the user as the macro is being executed.
For example, a message box can let the user know what task is about to happen or
ask the user for permission to proceed.
If the Message box contains multiple options (see Buttons argument below), additional VB code is required to process the buttons. One method would be an IF
ThenElse statement (see topic further on).
The syntax for the Message box consists of the following:
Name=MsgBox(prompt,buttons,title,helpfile,context)
Argument

18

Required/Optional

Prompt

Required!

Buttons

Optional

Description
Text that will appear as the message in
the Message box (up to 1,024 characters). Must be entered in doublequotes.
Specifies the number of buttons and the
type of buttons to display. If not specified an OK button will display by default.

Title

Optional

Helpfile

Optional

Context

Required
(if Helpfile argument is used)

Value
Button Type(s)
0
OK
1
OK, Cancel
2
Abort, Retry, Ignore
3
Yes, No, Cancel
4
Yes, No
5
Retry, Cancel
Text that will appear in the Title Bar of
the Input box dialog. Must be entered
in double-quotes.
Specifies the help file (if created) to display if a Help button (added to the Message box automatically)
Specifies help context number assigned
by author to the help file.

Microsoft Excel 2007 - Automation Through Macros - Dash Designs Consulting

CHAPTER

Making Macros More Flexible

USING MESSAGE BOXES IN MACROS

Example of Message Box Macro:

Sub OpenWkbk()
'
' OpenWkbk Macro
' Macro recorded 11/1/2007 by Jerry Maletsky Opens the Specified Workbook
'
' Keyboard Shortcut: Ctrl+Shift+O
'
Info = MsgBox("You are about to open a workbook")
OpenBk=InputBox(Enter the name of the workbook to open,Open Workbook)
Workbooks.Open Filename:= (OpenBk)
End Sub

Microsoft Excel 2007 - Automation Through Macros - Dash Designs Consulting

19

CHAPTER

Making Macros More Flexible

2
USING IFTHENELSE STATEMENTS IN MACROS

IFThenElse Statements can help process options set by the user such as in a message box with multiple buttons.
The syntax for the IFThenElse Statement consists of the following:
If condition Then
Statements
Else
Else Statements
End If
When there are more than 2 options available the ElseIf argument can be used:
If condition Then
Statements
ElseIf
ElseIf Statements
Else
Else Statements
End If

Argument

20

Required/Optional

Description

Condition

Required!

Specifies a condition that can


be tested as True or False

Statements

Required!

Specifies actions to be taken if


the condition is True

Else Statements

Required!

Specifies actions to be taken if


the condition is False

Microsoft Excel 2007 - Automation Through Macros - Dash Designs Consulting

CHAPTER

Making Macros More Flexible

USING IFTHENELSE STATEMENTS IN MACROS

Example of IFThenElse Statement Macro:


Sub FormatValues()
'
' FormatValues Macro
' Recorded by Jerry Maletsky on 11/4/2007 Selects specified cells. Formats numbers
based on button clicked in Message box.
'
'
SelectCells = InputBox("Enter cell range to select for formatting", "Select Cells")
DataFormat = MsgBox("Click Yes to format with Currency and 2 Decimal Places.
Click No to format without Currency symbol and 1 decimal place. Click Cancel to do
nothing.", 3, "Formatting Options")
If DataFormat = vbYes Then
Range(SelectCells).Select
Selection.NumberFormat = _
"_([$$-409]* #,##0.00_);_([$$-409]* (#,##0.00);_([$$-409]* ""-""??_);_
(@_)"
ElseIf DataFormat = vbNo Then
Range(SelectCells).Select
Selection.Style = "Comma"
Selection.NumberFormat = "_(* #,##0.0_);_(* (#,##0.0);_(* ""-""??_);_(@_)"
Else
Range("A1").Select
End If
End Sub

Microsoft Excel 2007 - Automation Through Macros - Dash Designs Consulting

21

CHAPTER

Making Macros More Flexible

2
USING IFTHENELSE STATEMENTS IN MACROS

Worksheet before formatting macro

Worksheet after formatting macro

22

Microsoft Excel 2007 - Automation Through Macros - Dash Designs Consulting

CHAPTER

Making Macros More Flexible

NAVIGATING AND SELECTING CELLS WITH THE KEYBOARD


One of the limitations of an Excel Macro is that it records the steps you perform literally (i.e. selecting a cell range). However, one method you can use to make the
selection of cells more flexible is to use the keyboard to select cells rather than the
mouse.

Navigating With The Keyboard

Navigation

Direction

One cell in that direction

Ctrl+Home

Goes To Cell A1 in that worksheet

Ctrl+End

Goes to the intersection of the last used row &


column

Ctrl+

Beginning And End Of A Cell Range In That


Direction

Ctrl+
Ctrl+
Ctrl+

Selecting Cells With The Keyboard

Hold Shift And Press On Any Of The Following Keyboard Keys


Selects One Cell In That Direction

Ctrl+End

Selects From Current Cell To End Of Worksheet

Ctrl+

Selects Cells From Beginning To End Of A Cell


Range In That Direction

Ctrl+
Ctrl+
Ctrl+

Microsoft Excel 2007 - Automation Through Macros - Dash Designs Consulting

23

CHAPTER

Making Macros More Flexible

2
ASSIGNING A MACRO TO A TOOLBAR OR MENU

To make macros more easily accessible, they can be assigned to toolbars or menus.
In addition, they can be assigned to graphic images (buttons, pictures) placed on the
worksheet.
Generally macros assigned to toolbars or menus are stored in the Personal Macro
Workbook, while macros assigned to buttons or images on a worksheet are generally stored in the This Workbook option.

Assigning a Macro To The Quick Access Toolbar

Steps:
Click Quick Access Toolbar Customize Button
Click The More Commands Option
From Choose Commands From list (top left), Choose Macros
Select the Macro from the displayed list
To Change Button Image and Name, click Modify button
Click OK

24

Microsoft Excel 2007 - Automation Through Macros - Dash Designs Consulting

CHAPTER

Making Macros More Flexible

ASSIGNING A MACRO TO A TOOLBAR OR MENU

Macro Added To The


Quick Access Toolbar

Macro Display Name

Microsoft Excel 2007 - Automation Through Macros - Dash Designs Consulting

25

CHAPTER

Making Macros More Flexible

2
ASSIGNING A MACRO TO A WORKSHEET BUTTON OR IMAGE

In addition to assigning a macro to a toolbar or menu command, a macro can also


be assigned to a button or an image on the worksheet itself. This can be a very efficient way to access a macro that only runs inside that workbook.
Before the macro can be assigned, a button has to be drawn onto the worksheet
(Insert Tab: Shape command) or an image needs to be inserted into the worksheet
(Insert Tab: Picture (or ClipArt)).

Assigning a Macro To A Worksheet Button or Image

Steps:
Assigning a Macro To A Worksheet Button

Place image on worksheet (i.e. Picture or Shape)


Right-click on new button, Select Assign Macro Command
Select the preferred macro
Click OK

26

Microsoft Excel 2007 - Automation Through Macros - Dash Designs Consulting

CHAPTER

Making Macros More Flexible

ASSIGNING A MACRO TO A WORKSHEET BUTTON OR IMAGE

Microsoft Excel 2007 - Automation Through Macros - Dash Designs Consulting

27

Das könnte Ihnen auch gefallen