MarcoMarcoMarcoMarcoMarco
-
Upload
angell-eduardo-razuri-buchelli -
Category
Documents
-
view
220 -
download
0
description
Transcript of MarcoMarcoMarcoMarcoMarco
-
M O
D U
L E
7
DASH DESIGNS CONSULTING
Technology Training and Consulting Services
Microsoft Excel 2007Microsoft Excel 2007
AutomationAutomation ThroughThrough MacrosMacros
-
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
Copyrights and Trademarks
2007, Dash Designs Consulting, Jerry Maletsky
San Rafael, CA 94903
email: [email protected] web site: www.dashdesignsconsulting.com
fax (415) 491-1490
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
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.
Revised: November 4, 2007
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, UC Berkeley Dash Designs Consulting
Table of Contents
Planning and Recording Macros ... 4
Making Macros Flexible .............. 16
Reference Workbook: Macros Workbook.xlsx
Excel 2007Excel 2007 Automation Through MacrosAutomation Through Macros
-
C H
A P
T E
R
1 Microsoft Excel 2007 - Automation Through Macros - Dash Designs Consulting
1
Jerry Maletsky
Dash Designs Consulting
Technology Training and Consulting
Microsoft Excel 2007Microsoft Excel 2007
Automation Automation ThroughThrough MacrosMacros
-
Microsoft Excel 2007 - Automation Through Macros - Dash Designs Consulting
C H
A P
T E
R
2
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
1 Planning and Recording Macros
-
C H
A P
T E
R
3 Microsoft Excel 2007 - Automation Through Macros - Dash Designs Consulting
Planning and Recording Macros
1
EXCEL 2007 MACRO SECURITY
For more information on
Macro Security see Micro-
soft Excel Help System.
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
-
Microsoft Excel 2007 - Automation Through Macros - Dash Designs Consulting
C H
A P
T E
R
4
SETTING MACRO SECURITY
1 Planning and Recording Macros
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 Office takes precautions before opening files that contain macros. That is be-
cause 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 be-
fore a file can be opened to opening any file regardless whether or not they contain mac-
ros.
Security settings can be viewed in Microsoft Excel through the, OOFFICEFFICE BBUTTONUTTON,
EEXCELXCEL OOPTIONSPTIONS BBUTTONUTTON, T, TRUSTRUST CCENTERENTER, MMACROACRO SSETTINGSETTINGS command.
-
C H
A P
T E
R
5 Microsoft Excel 2007 - Automation Through Macros - Dash Designs Consulting
SETTING MACRO SECURITY
Trust Center Dialog Box
Planning and Recording Macros
1
Macro Settings Dialog Box
-
Microsoft Excel 2007 - Automation Through Macros - Dash Designs Consulting
C H
A P
T E
R
6
Planning and Recording Macros
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
MMACROACRO NNAMEAME::
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.
SSHORTCUTHORTCUT KKEYEY: : (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.
SSTORETORE MMACROACRO IINN::
This Workbook ( macro can only be run in the workbook it is being recorded in
or when that workbook is opened)
Personal Macro Workbook (global macro can run in any workbook)
New Workbook (macro is stored in a separate workbook that must be opened
in order to run it)
DDESCRIPTIONESCRIPTION: : (Optional)
Enter a summary description that will help recall what tasks the macro performs.
-
C H
A P
T E
R
7 Microsoft Excel 2007 - Automation Through Macros - Dash Designs Consulting
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
Planning and Recording Macros
1
View Tab: Macros: Record New Macro Dialog Box
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.
Great Tip!
RECORDING A MACRO
-
Microsoft Excel 2007 - Automation Through Macros - Dash Designs Consulting
C H
A P
T E
R
8
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 exe-
cuted 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 navi-
gate 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 oth-
ers 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.
-
C H
A P
T E
R
9 Microsoft Excel 2007 - Automation Through Macros - Dash Designs Consulting
Planning and Recording Macros
1
RECORDING ABSOLUTELY OR RELATIVELY
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
Use Relative References Command
View Tab: Macros Command
Command is On - Relative Reference
Command is Off - Absolute Reference
-
Microsoft Excel 2007 - Automation Through Macros - Dash Designs Consulting
C H
A P
T E
R
10
Planning and Recording Macros
1
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 us-ing 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
-
C H
A P
T E
R
11 Microsoft Excel 2007 - Automation Through Macros - Dash Designs Consulting
Planning and Recording Macros
1
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 per-formed (i.e. Range (B10).Select ). More complex steps have to be writ-ten 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
C H
A P
T E
R
12
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 per-
formed 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
Planning and Recording Macros
-
C H
A P
T E
R
13 Microsoft Excel 2007 - Automation Through Macros - Dash Designs Consulting
1
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, Micro-
soft 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
Planning and Recording Macros
-
Microsoft Excel 2007 - Automation Through Macros - Dash Designs Consulting
C H
A P
T E
R
14
1
ADDING MORE COMMANDS TO A MACRO
Planning and Recording Macros
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
-
C H
A P
T E
R
15 Microsoft Excel 2007 - Automation Through Macros - Dash Designs Consulting
1 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
C H
A P
T E
R
16
2
ADDING INTERACTIVE DIALOG BOXES
Making Macros More Flexible
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 func-
tion 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 Required/Optional Description
Prompt Required! Text that will appear as the message in
the Input box (up to 1,024 characters).
Must be entered in double-quotes.
Title Optional Text that will appear in the Title Bar of
the Input box dialog. Must be entered
in double-quotes.
Default Optional Specifies entry to be entered by default.
Must be entered in double-quotes.
Xpos Optional Specifies the horizontal position from the
left edge of the Input box to the left
edge of the screen.
Ypos Optional Specifies the vertical position from the
top edge of the Input box to the top
edge of the screen
Helpfile Optional Specifies the help file (if created) to dis-
play if a Help button (added to the Input
box automatically)
Context Required
(if Helpfile argument is
used)
Specifies help context number assigned
by author to the help file.
-
C H
A P
T E
R
17 Microsoft Excel 2007 - Automation Through Macros - Dash Designs Consulting
Making Macros More Flexible
2
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 Work-book) Workbooks.Open Filename:= (OpenBk) End Sub
-
Microsoft Excel 2007 - Automation Through Macros - Dash Designs Consulting
C H
A P
T E
R
18
2
USING MESSAGE BOXES IN MACROS
Making Macros More Flexible
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), addi-tional VB code is required to process the buttons. One method would be an IFThenElse statement (see topic further on).
The syntax for the Message box consists of the following:
Name=MsgBox(prompt,buttons,title,helpfile,context)
Argument Required/Optional Description
Prompt Required! Text that will appear as the message in
the Message box (up to 1,024 charac-
ters). Must be entered in double-
quotes.
Buttons Optional Specifies the number of buttons and the
type of buttons to display. If not speci-
fied an OK button will display by default.
Value Button Type(s)
0 OK
1 OK, Cancel
2 Abort, Retry, Ignore
3 Yes, No, Cancel
4 Yes, No
5 Retry, Cancel
Title Optional Text that will appear in the Title Bar of
the Input box dialog. Must be entered
in double-quotes.
Helpfile Optional Specifies the help file (if created) to dis-
play if a Help button (added to the Mes-
sage box automatically)
Context Required
(if Helpfile argument is used)
Specifies help context number assigned
by author to the help file.
-
C H
A P
T E
R
19 Microsoft Excel 2007 - Automation Through Macros - Dash Designs Consulting
Making Macros More Flexible
2
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
C H
A P
T E
R
20
2
USING IFTHENELSE STATEMENTS IN MACROS
Making Macros More Flexible
IFThenElse Statements can help process options set by the user such as in a mes-sage 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 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
-
C H
A P
T E
R
21 Microsoft Excel 2007 - Automation Through Macros - Dash Designs Consulting
Making Macros More Flexible
2
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
C H
A P
T E
R
22
2 Making Macros More Flexible
USING IFTHENELSE STATEMENTS IN MACROS
Worksheet before formatting macro
Worksheet after formatting macro
-
C H
A P
T E
R
23 Microsoft Excel 2007 - Automation Through Macros - Dash Designs Consulting
Making Macros More Flexible
2
One of the limitations of an Excel Macro is that it records the steps you perform lit-
erally (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 AND SELECTING CELLS 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+
Ctrl+
Ctrl+
Ctrl+
Beginning And End Of A Cell Range In That
Direction
Navigating With The Keyboard
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 Work-
sheet
Ctrl+
Ctrl+
Ctrl+
Ctrl+
Selects Cells From Beginning To End Of A Cell
Range In That Direction
-
Microsoft Excel 2007 - Automation Through Macros - Dash Designs Consulting
C H
A P
T E
R
24
ASSIGNING A MACRO TO A TOOLBAR OR MENU
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
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 gener-
ally stored in the This Workbook option.
Assigning a Macro To The Quick Access Toolbar
2 Making Macros More Flexible
-
C H
A P
T E
R
25 Microsoft Excel 2007 - Automation Through Macros - Dash Designs Consulting
ASSIGNING A MACRO TO A TOOLBAR OR MENU
Making Macros More Flexible
2
Macro Added To The
Quick Access Toolbar
Macro Display Name
-
Microsoft Excel 2007 - Automation Through Macros - Dash Designs Consulting
C H
A P
T E
R
26
2 Making Macros More Flexible
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 ef-
ficient 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)).
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
Assigning a Macro To A Worksheet Button or Image
-
C H
A P
T E
R
27 Microsoft Excel 2007 - Automation Through Macros - Dash Designs Consulting
Making Macros More Flexible
2
ASSIGNING A MACRO TO A WORKSHEET BUTTON OR IMAGE