Using Macros
2016
60 Pages
About IT Training
The University Information Technology Services (UITS) IT Training program at Indiana University offers instructorled computing workshops and self-study training resources to the Indiana University community and beyond. We
deliver training to more than 50,000 participants annually across all Indiana University campuses. Our staff is comprised of enthusiastic professionals who enjoy developing and teaching computing workshops. We
appreciate your feedback and use it to improve our workshops and expand our offerings. We have received several
international awards for our materials and they are being used at universities across the country.
Please keep your questions, comments and suggestions coming!
(812) 855-7383
(312) 274-7383
ittraining@iu.edu
http://ittraining.iu.edu
http://ittrainingtips.iu.edu/
http://facebook.com/ittrainingiu
http://twitter.com/ittrainingiu
http://pinterest.com/ittrainingiu
http://instagram.com/ittrainingiu
Contents
Welcome and Introduction . . . . . . . . . . . . . . . .
What You Should Already Know . . . . . . . . . .
What You Will Learn . . . . . . . . . . . . . . . .
What You Will Need to Use These Materials . . . .
Getting Started . . . . . . . . . . . . . . . . . . . . . .
Todays Project . . . . . . . . . . . . . . . . . . . . . .
About These Materials for MacOS Users . . . . . .
Creating a Macro . . . . . . . . . . . . . . . . . . . . .
Opening a File . . . . . . . . . . . . . . . . . . . .
Recording a Macro . . . . . . . . . . . . . . . . . .
Turning on Excels Recorder for Windows . . .
Storing Macros . . . . . . . . . . . . . . . . . .
Storing Macros . . . . . . . . . . . . . . . . . .
Recording a Sequence of Actions . . . . . . . .
Running the Macro. . . . . . . . . . . . . . . . . . . .
Using the Macro Dialog Box. . . . . . . . . . . . .
Using the Control Key . . . . . . . . . . . . . .
Adding a Macro to the Quick Access Toolbar . . . .
Adding a Macro to the Quick Access Toolbar on
Windows . . . . . . . . . . . . . . . . . . .
Changing the Icon and Name of a Button . . . .
Adding a Macro to the Quick Access Toolbar on
MacOS . . . . . . . . . . . . . . . . . . . .
Using the Quick Access Toolbar to Run a Macro
Using an Auto_Open Macro on Windows . . . . . . . .
Using an Auto_Open Macro on MacOS . . . . . . . . .
Saving the Workbook . . . . . . . . . . . . . . . . . .
Understanding File Formats in Excel 2016 . . . . .
Understanding Macro Security. . . . . . . . . . . . . .
Using the Trust Center . . . . . . . . . . . . . . . .
Setting Trusted Locations on Windows . . . . .
Testing the Trust Center Settings . . . . . . . .
Setting Security and Privacy on MacOS . . . . .
Best Practices in Macro Security. . . . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
. 5
. 5
. 5
. 5
. 6
. 7
. 7
. 7
. 8
. 9
. 10
. 11
. 13
. 13
. 15
. 15
. 15
. 16
. . 16
. . 18
.
.
.
.
.
.
.
.
.
.
.
.
. 20
. 22
. 23
. 25
. 26
. 28
. 29
. 30
. 30
. 36
. 37
. 37
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
. 37
. 38
. 39
. 39
. 40
. 41
. 41
. 42
. 44
. 45
. 46
. 46
. 47
. 49
. 49
. 49
. 50
. 50
. 51
. 53
. 54
. 55
. 56
. 58
. 58
. 59
. 59
. 61
. 61
. 62
. 63
. 64
. 64
Getting Started
These materials presume you will begin work from the desktop, and have any required
exercise files located in an epclass folder there.
http://ittraining.iu.edu/downloads/
Once you are logged on and have the needed files in an epclass folder on your desktop,
you are ready to proceed with the rest of the workshop.
Finding Help
If you have computer-related questions not answered in these materials, you may look
for the answers in the UITS Knowledge Base, located at:
http://kb.iu.edu/
Self-study training: You may access computer-based training from leading commercial vendors, obtain the materials for other IT Training workshops, or access IT Trainings own tutorials on a range of topics at:
http://ittraining.iu.edu/online/
IT Training Tips weblog: Our award-winning blog has short tutorials and training
posts on a broad range of topics and technologies. Its written by training and support
providers from across the entire IU system; you may read and comment on these at:
http://ittrainingtips.iu.edu/
Todays Project
In todays workshop, we will be exploring the use of macros in Microsoft Excel 2016,
part of the Microsoft Office 2016 office suite. A macro is a series of recorded instructions which mimic the actions required to perform a task. Excel allows a series of
actions to be recorded as they are performed, which it then translates into Visual Basic
for Applications, or VBA, code for that macro. If a task must be performed repeatedly
in Excel, a macro for that task will perform it with precision and consistency.
Well learn how to create basic macros, how to edit the Visual Basic relating to these
macros and security considerations when using macros in Excel. To do this, we will be
using a workbook that is designed to track purchases for a small business.
http://ittrainingtips.iu.edu/?p=10227
If you have not made this change, not all instructions in these materials may behave as
expected on your computer. If this happens, you may have to perform some simple
substitutions. The following table lists common substitutions between the Windows
and MacOS operating systems:
On Windows
On MacOS
C ONTROL KEY
C OMMAND KEY
A LT KEY
O PTION KEY
E NTER
R ETURN
R IGHT -C LICK
Creating a Macro
Macros can be stored in a single workbook file, available only to sheets in that workbook, or they can be stored in a global file so that they are available to all workbooks.
Well start by recording a basic macro and storing it in the Personal Macro Workbook.
Opening a File
Well start by launching Excel.
1. Launch Excel.
Excel loads and displays recent documents that have been opened, as well as
several templates. For our workshop, well need to open a file called macroex.xlsx.
2. To open an existing file,
CLICK
4. To browse for the files,
CLICK
NOTE for MacOS Users: On the Mac, CLICK
You see the Open dialog box.
We need to specify the name and location of the file to open.
CLICK
The current location is now set to the desktop. All of our exercise files are contained in the epclass folder, located on the desktop.
2. To open the epclass folder,
DOUBLE-CLICK
The epclass folder contents are now visible.
We will need to open the Excel Macros subfolder of the epclass folder that
contains all of the necessary documents.
3. To open the correct folder,
DOUBLE-CLICK macroex.xlsx
You see four different worksheets, each of which contains a database listing expenses for a different year.
Recording a Macro
Macros are written in a programming language called Visual Basic for Applications,
or VBA; however, knowledge of this language isnt required to create and use simple
macros. When a series of actions is recorded, Excel translates them into VBA code as
they are performed.
When Excel records a macro, it retains the sequence of keystrokes and menu selections so they can be repeated as needed. This process is very much like recording a
voice with a tape recorder and then listening to it later as it plays back. When the
macro is run, Excel exactly repeats the recorded steps, mistakes and all.
When the workbook is opened, some of the columns are not wide enough to show all
of their contents. The first macro we will record will fix this.
CLICK
AutoFit TAB
KEY
Notice that we didnt type a space in the macro name. Spaces are not allowed
in macro names. Macro names must also start with a letter, and macros cannot
be named after a cell reference, i.e., A1.
NOTE: Pressing T AB KEY moved the cursor to a new field where we can define a
control key combination that can be used to launch the recorded macro.
10
SHIFT
KEY+A,
then TAB
KEY
NOTE: Assigning a shortcut that is identical to a keyboard shortcut that already exists
in Excel will overwrite that shortcut on a Windows computer. For example, if
we had assigned the shortcut C ONTROL KEY + A to this macro, the select all
keyboard shortcut would no longer function. Mac users will encounter a
warning message if they try to override a pre-existing keyboard shortcut.
Storing Macros
Macros can be stored in three locations: in this workbook, in a new workbook, or in
the personal macro workbook. The list below points out the benefits of each storage
option:
This WorkbookMacros stored in the current workbook are only accessible when
the workbook is open. This option is good for macros that will only be used within a
certain file.
New WorkbookMacros stored in a new workbook have the same restrictions and
benefits of macros stored in the current workbook; theyre just stored in a new workbook.
Personal Macro WorkbookMacros stored in the Personal Macro Workbook are
accessible to any workbook opened in Excel. The Personal Macro Workbook is a hidden workbook that is always opened when Excel is opened.
Since this macro is useful to any workbook we have open, we will select the Personal
Macro Workbook.
1. To select Personal Macro Workbook and move to the description field, if
necessary,
CLICK
KEY
It is always a good idea to document the macro by providing a description stating exactly what the macro does.
2. To enter a description of the macro, type:
11
3. To begin recording,
CLICK
A tape recorder-like stop button displays in the status bar of the worksheet, indicating that the macro has begun recording. Any action now taken will be recorded by Excel.
CLICK
You see the Record Macro dialog box:
12
AutoFit TAB
KEY
Storing Macros
Since this macro is useful to any workbook we have open, we will select the Personal
Macro Workbook.
1. To select Personal Macro Workbook,
CLICK
KEY
NOTE: Keyboard shortcuts for macros do not always work on the Mac. You may try
to use one, but your results may vary.
2. To enter a description of the macro, type:
CLICK
A tape recorder-like stop button displays in the status bar of the worksheet, indicating that the macro has begun recording. Any action now taken will be recorded by Excel.
13
CLICK
The whole worksheet is selected.
2. To resize all the columns at once,
DOUBLE-CLICK
Now that were done recording, its good practice to select a cell where we
would like our cursor to be when were done running the macro. For our purposes, lets select A1.
3. To place the cursor in the first cell of the worksheet,
CLICK cell A1
Now that we have recorded the tasks we wanted to automate, we will turn off
Excels recorder.
CLICK
The actions have been recorded as the content of the AutoFit macro.
14
CLICK
15
CONTROL
KEY+SHIFT KEY+A
NOTE for MacOS Users: Use the Macros dialog box from the View tab to run the
macro.
The macro runs and the new data is sorted.
16
The left column contains all the commands that can be added to the Quick Access Toolbar, and the right column lists the commands already on the toolbar.
We will need to find our macros in the left column and place them in the right
column.
17
3. To find macros in the choose commands from drop-down list on the left,
CLICK
, CLICK Macros
DOUBLE-CLICK <Separator>
We see <Separator> in the right column. We will now add our macro to the
Quick Access Toolbar as well.
5. To add AutoFit to the Quick Access Toolbar, in the left column,
DOUBLE-CLICK PERSONAL.XLSB!AutoFit
AutoFit is now added to the Quick Access Toolbar. Lets explore modifying it
further.
CLICK PERSONAL.XLSB!AutoFit
The AutoFit macro is selected.
18
CLICK
You see the Modify Button dialog box:
Auto Fit
6. To make the change,
CLICK
We are returned to the Customize window.
19
CLICK
We now see a separator and a button with the icon we created.
NOTE: To remove a command button from the Quick Access Toolbar, R IGHT C LICK the button and select Remove from Quick Access Toolbar.
20
CLICK
You see the Ribbon & Toolbar dialog box.
NOTE: Alternatively, click the downward arrow on the right of the Quick Access
Toolbar to access the Ribbon & Toolbar Preferences dialog box.
21
3. To customize the Quick Access Toolbar, find macros in the choose commands
from drop-down list on the left,
CLICK
, CLICK Macros
22
CLICK
Our workbook is saved. It would be nice if this macro was run when this workbook is opened. Lets see how this is done.
CLICK
We see the Record Macro dialog box.
2. To enter the macro name, type:
Auto_Open, TAB
KEY,
TAB
KEY
We dont need a keyboard shortcut key for an Auto_Open macro. We will save
this macro in this workbook so that it doesnt interfere with every workbook we
open on this computer.
23
3. If necessary, to select This Workbook and move to the description field, press:
CLICK
KEY
CLICK
We have already recorded the tasks that we want performed in our AutoFit macro. We can simply play back the AutoFit macro now and Excel will record us
playing it back.
6. To play the AutoFit macro, press:
CONTROL
KEY+SHIFT KEY+A
Running another macro while recording a macro captures the running of a macro inside another macro. This shortens the amount of time needed to record a
macro and minimizes the amount of code needed to record the new macro.
7. To stop the recorder, in the status bar,
CLICK
The actions have been recorded as the content of the Auto_Open macro. Keep
in mind that since we recorded playing back a macro that is located in our Personal Macro Workbook, this macro will not function on another computer unless we send along our Personal Macro Workbook with it.
24
CLICK
We see the Record Macro dialog box.
2. To complete the setup for this Macro, input the following data into the appropriate areas in the Record Macro dialog box.
Dialog Box Labels
Data to Enter
Macro name:
Auto_Open
This Workbook
Description
CLICK
We cant record the running of a macro, so lets stop recording and add the code
manually.
4. To stop recording, in the status bar,
CLICK
The code we need to add is relatively simple, so lets open the macro to edit,
make the change, then close the Visual Basic Editor.
25
The macro opens in the Visual Basic Editor. Lets add the code that runs the
AutoFit macro now.
6. To add the code that will run the AutoFit macro in the Auto_Open macro, type
the code shown in bold below:
Sub Auto_Open()
'
'Auto_Open Macro
'A macro to automatically fit cells to their data when a workbook is
opened.
Application.Run "'Personal Macro Workbook'.xlsb!AutoFit"
End Sub
26
1. Make various column widths more narrow so the macro can run.
Saving workbooks in Excel 2016 is not as simple as it was in previous versions
of Excel. When Microsoft switched to Open XML formats for their files, they
also introduced macro-enabled and non-macro-enabled formats. Since we created macros in our workbook, we must now save it as a macro-enabled Excel
file (*.xlsm).
We will begin saving this workbook using the Save button on the Quick Access
Toolbar. When we use this button, the Save command in the FILE tab, or a keyboard shortcut, Microsoft Excel gives us the option to save the workbook without macros or to save the workbook in the new macro-enabled file format.
2. To begin saving the workbook, on the Quick Access Toolbar,
CLICK
You see this warning:
NOTE for MacOS Users: On the Mac, you will see this dialog box:
CLICK
27
CLICK
NOTE: We may choose no from the warning, but if we dont change this file format,
we will still save a file without preserving the macro information.
2. To keep the original filename and the new file format,
CLICK
NOTE for MacOS Users: On the Mac, C LICK
, C LICK
28
DOUBLE-CLICK macroex.xlsm
You will notice that nothing has happened yet, but you will see a security warning below the ribbon:
NOTE for MacOS Users: Mac Users will see this dialog box instead:
29
CLICK
NOTE for MacOS Users: On the Mac, C LICK
NOTE: Be careful when enabling content because the content might contain macros
that could contain viruses. Be certain to regularly scan your computer with a
recently updated version of anti-virus software, and to keep the virus definitions for that software updated regularly, as well.
You will now see our macro run and the columns that we narrowed become the
correct widths again. We will now explore macro security and the Trust Center.
https://msdn.microsoft.com/en-us/library/mt654019.aspx
30
31
CLICK
You see the Trust Center dialog box:
NOTE: Your screen may look slightly different depending on the last section that has
been viewed on your machine.
The sections of the trust center are listed in the navigation pane.
The following table describes in detail what type of settings can be changed in
32
each section:
Section
Description
Trusted Publishers
Trusted Locations
Trusted Documents
Trusted App
Catalog
Add-ins
Add-ins settings allow the user to designate whether or not add-ins must be signed
by a trusted publisher. It also contains an
option to disable all application add-ins.
ActiveX Settings
Macro Settings
Protected View
Allows files from potentially unsafe locations to be opened, inspected, and reviewed while minimizing risk to your
machine.
33
Section
Description
Message Bar
External Content
External Content controls how Excel handles connections to external data or external workbooks.
Prevents out-dated documents from opening and can cause a file to be opened in
Protected View. Opening some of these
formats can cause your machine to be vulnerable to attacks.
Privacy Options
Privacy Options control how Excel connects to online help and how the online
help content is managed. It also allows the
user to remove personal data from files
when they are saved.
34
CLICK
You see:
CLICK
We see the Browse dialog box.
7. Navigate to the epclass folder.
8. To select the subfolder,
35
TAB
KEY
CLICK
This is all we are doing in the Trust Center today.
NOTE: These settings will be used from this point forward on this machines installation of Excel.
13. To exit the Trust Center,
CLICK
, CLICK
36
CLICK
You see the Security & Privacy dialog box:
3. Make sure the button Warn me before opening a file that contains macros is
selected.
4. Close the window
37
was found, it would create one and copy itself to the workbook. Laroux would then
copy itself to every workbook created from that point forward, infecting every file created on a specific machine.
Another popular macro-driven virus was W97M.Melissa, or Melissa for short. This
virus started making its rounds in the late 90s/early 2000s. Melissa infected Microsoft
Word, disabling the applications default macro detection. After infecting Word, it
would use Outlook or Outlook Express to mail itself to the first 50 people in each
address book. It also added itself, much like Laroux did, to each file created in Word
from then on, making its spread quite rapid. When this virus was initially introduced, it
was known for bringing mail servers and company intranets down under massive
demands on the networks' bandwidth.
It may seem like these viruses are so old that mentioning them makes the content of
this workshop outdated. The reality is that both of these viruses are still in use today as
a method of delivering a more sophisticated malware payload. For example, someone
with malicious intent can use Laroux to as an entry point into an unsecured machine
and then propogate the spread of some other, more sophisticated, or more malicious
virus by making a few changes to the macro's code. The piggybacking malware doesn't
need to be a macro, but could be a standalone program.
Avoid implicit trustThe notion of trusting a publisher is one of the key ways to
protect yourself from malicious macros. If you receive a file from someone you dont
know that contains a macro, chances are it is not a safe macro. These macros should
not be run without great care being taken to protect yourself.
Dont trust surprise filesWhen you receive a file from a colleague that contains
macros, it shouldnt be a surprise. You should already have an idea that the file is
coming and it should appear to be for a legitimate purpose. If you receive a file that
you are not expecting, it is best to be suspicious of its content until it can be verified
in a separate message.
Do not enable questionable contentProbably the best advice to protect yourself
from macro-virus infection is to not enable questionable content, especially if the file
is questionable. Microsoft Office 2016 allows the data in a file to be manipulated
without enabling possibly malicious content and in most cases, the content is what is
being shared, not the automation built into the file.
The bottom line to protect yourself is to question the validity of macro-enabled files
sent to you and always verify that the file is intended to be sent to you. As we learned
in the Melissa example, a macro virus can use other applications to propagate itself via
email or other means.
38
For more information about macro security, visit the following link to the Knowledge
Base:
http://kb.iu.edu/data/agzl.html
CLICK
We see the Record Macro dialog box.
2. To enter the macro name, type:
DataSorter TAB
KEY
Notice that we didnt type a space in the macro name. Spaces are not allowed
in macro names.
39
CLICK
KEY
SHIFT
KEY+ D,
TAB
KEY
Since we only need this macro to be available to this workbook, well choose
This Workbook.
5. To enter a description of the macro, type:
CLICK
Lets take a look at the actions we will record.
CLICK
We see the Record Macro dialog box.
40
2. To complete the setup for this Macro, input the following data into the appropriate areas in the Record Macro dialog box.
Dialog Box Labels
Data to Enter
Macro name:
DataSorter
This Workbook
Description
3. To begin recording,
CLICK
Lets take a look at the actions we will record.
Sorting
To find the subtotals of each expense class, we must first sort the data in expense
order. The first step in this process is to choose the active cell. If we select an active
cell in the list as the first action, the macro will always begin using that particular cell,
regardless of where the active cell is when the macro is triggered. We only need to
select a cell in the range because Excel will automatically select all adjacent cells
when the sort function is used.
1. To select a cell in the list,
41
CLICK
NOTE for MacOS Users: On the Mac, C LICK
You see the Sort window:
CLICK
, CLICK Expense
CLICK
The table is sorted by Expense.
Calculating Subtotals
Now we can total the expense groups using the Subtotal tool. The Subtotal tool in
Excel will summarize data in a sorted list. Each column should contain the same data
type and have an assigned label like the first row of our data. We will create subtotals
to show how much we are spending in each category listed in the worksheet.
42
1. To select the Subtotals option, in the Outline group on the right side of the
Data tab,
CLICK
You see the Subtotal dialog box:
We want Excel to calculate the Sum total in the Amount field every time the
expense category changes. To do this, we will select the appropriate settings.
43
Change to:
Expense
Use Function
Sum
Amount
CLICK
We see that our data is sorted by expense type and each expense group has its
own subtotal.
44
CLICK
The actions have been recorded as the content of the DataSorter macro.
You see subtotals displayed along with your data. Numbered buttons (
)
also appear in the worksheets far left column. Button 1 will display the Grand
Total, button 2 will display Subtotals, and button 3 will show all data.
2. Save your document.
CONTROL
KEY+SHIFT KEY+D
NOTE for MacOS Users: To run the macro, use the View Macros dialog box from the
View tab of the Ribbon.
We see an error message:
Excel is telling us that if we continue, the 2003 worksheet will be reset, causing
all our sorting and subtotaling in the 2003 worksheet to be removed. This error
is caused by the way the macro is translated to VBA code. We dont want to do
this because it is a sign that something in our macro isnt functioning as we
wanted it to. We cant do anything about it now, but we will see how to fix this
problem in the next section.
45
CLICK
We now see a Visual Basic runtime error message:
CLICK
NOTE for MacOS Users: On the Mac, C LICK
We will work on fixing this error in a few minutes, but to do so, we need to become acquainted with the Visual Basic Editor and how macro code is structured.
must always be run from within the program that created it. VBScript is the newest
dialect of Visual Basic, and it competes with JavaScript in the dynamic HTML/Internet area.
The code that is generated when a macro is recorded is Visual Basic and VBA code
since the language syntax is nearly identical. The only distinction is that the macros
we recorded can only be run from Excel.
In order to get a better idea of how macros work, lets look at the VBA-coded version
of the DataSorter macro we just created.
CLICK
47
CLICK
A new window opens for Microsoft Visual Basic, a Microsoft application that
allows VBA code to be viewed and edited.
There are three sub-windows in the Microsoft Visual Basic window, but the relevant window shows the actual code itself, on the right side of the Microsoft
Visual Basic window.
The Visual Basic window below has been maximized to display the entire
DataSorter macro code:
Some careful reading will reveal the error in our code. We can see three places
where the macro recorder referenced our worksheet explicitly:
ActiveWorkbook.Worksheets("2003")
This is why when we tried to run the macro on the 2004 worksheet, we saw an
error message telling us that our project would be reset.
Lets explore the different parts of the macro code in more detail.
48
Comments
At the top of the module, you see the macro title and description written in green with
a single quotation mark (') before each line. This combination of color and coding
indicates that these are comments, which we created when we recorded the macro.
Comments are for documentation purposes only, they are not executed. This information can be changed without altering the operation of the macro. Note that the main
comment is the description we entered when recording the macro. This illustrates why
it is important to give a good description when recording a macro; it helps make the
recorded code easier to read.
Sub Statements
Above the comments, you see Sub DataSorter (), and beneath the comments is
a list of steps, ending with End Sub. All macros begin and end with Sub statements.
This tells Visual Basic that this is a sub procedure as opposed to Excels main procedures, which control program execution.
Statements
The list of statements which lie between the beginning and ending sub statements are
the steps we followed in creating the DataSorter macro.
Lets take a quick look at the steps to see how our actions were coded.
The first step we took was to select cell A10. This action is represented in VBA by the
following statement:
Range("A10").Select
Visual Basic refers to the different components of a statement as objects, properties,
and methods.
In the above example:
The currently active worksheet is the Object, which is not explicitly stated.
Range is a property of the current worksheet.
Select is the method being applied to the Range property.
A10 is the value of the specific cell being selected with the Select Method.
In other words, this command is selecting a new active cell by applying the Select
Method to the current Worksheet Objects Range property. Though the remainder of
the macro looks a little more complicated, it follows the same kind of syntax with a
few extra properties and methods thrown in.
49
Editing a Macro
Our original macro isnt very scalable. This is because Excel references the worksheet
we were working on by name. In the next section, well see what we can do to recognize this problem as well as repair it.
Making this simple change will allow us to run the macro on multiple worksheets
without resetting the 2003 worksheet every time.
1. To select the text to replace,
ActiveSheet
50
Any macro can be edited in the Visual Basic window or by copying and pasting
code from another macro.
4. Save the document.
51
CLICK
NOTE: You can also move back to Excel from within the Visual Basic application by
pressing A LT KEY +F11 KEY .
NOTE for MacOS Users: You can also move back to Excel from within the Visual
Basic application by pressing O PTION KEY + FN KEY +F11 KEY , or by
using the Window menu in the Menu bar to select the worksheet.
You should be back in the 2004 Worksheet. We need to switch to the 2003
worksheet where our data has already been manipulated.
2. To switch to the 2003 worksheet,
CLICK
NOTE for MacOS Users: On the Mac in the Status bar, C LICK
You see the Macro dialog box again. This time, we will accept the default name
(Macro#) since we will only be using it for a short time.
4. To set the macro to record into the This Workbook, if necessary,
CLICK
CLICK
The recorder console appears on the worksheet, and the status bar displays the
word Recording, indicating that Excel is recording your actions.
52
CLICK
You see the subtotals for the expense types and the grand total. All the rest of
the data is hidden. These totals were added when we ran the subtotal function
when recording our macro. We can see that some of our columns need to be resized to allow our data to fit. Lets capture the running of the AutoFit macro
into this code and make it part of DataSorter.
7. To run AutoFit, press:
CONTROL
KEY+SHIFT KEY+A
NOTE for MacOS Users: Mac users will have to manually add code to execute the
AutoFit macro using the Application.Run command as we did earlier.
Were done with this part of our macro, so lets stop recording.
8. To stop recording, in the Status bar,
CLICK
Our macro is finished, so lets move the code.
Moving Code
We now have a new macro which collapses the subtotals. Lets take a look at its code.
53
ALT
KEY+F11 KEY
NOTE for MacOS Users: You can also move back to Excel from within the Visual
Basic application by pressing O PTION KEY + FN KEY +F11 KEY , or by
using the Window menu in the Menu bar to select the worksheet.
You now see code for the new macro under the code for the DataSorter macro.
The new macro has the following lines of code:
ActiveSheet.Outline.ShowLevels RowLevels:=2
Application.Run "PERSONAL.XLSB!AutoFit"
NOTE for MacOS Users: On the Mac, we will have to add the Application.Run
code manually. The code to add is Application.Run "'Personal
Macro Workbook'.xlsb!AutoFit".
This Visual Basic statement tells Excel to act on the currently open sheet within
the data outline in order to display the subtotals only (level 2). This is the code
we want to make part of the DataSorter macro.
54
CLICK
You see a list of three items: (Declarations), DataSorter, and Macro#. The Declarations section is used to declare variables for the entire module. DataSorter
and Macro# are the names of the two macros in this module.
2. To move into another procedure, in the Procedure drop-down list,
CLICK DataSorter
The cursor moves into the Sub DataSorter statement at the top.
3. To move the cursor back to Macro#, in the Procedure drop-down list,
CLICK
, CLICK Macro#
CONTROL
KEY+C
55
ENTER, UP ARROW
KEY
The cursor should now be at the beginning of a blank line, just before the EndSub statement in the DataSorter macro.
5. To paste the code, press:
CONTROL
KEY+V
The DataSorter macro now includes the code to collapse the subtotals. We can
now remove the Macro# code from the code module.
6. To select the Macro# subroutine,
DELETE
KEY
The pasted code will be executed at the end of the DataSorter macro.
NOTE: The same procedure of copying and pasting code can be used to transfer any
workbook macro into the Personal Macro Workbook.
8. Save your document.
56
1. To make the changes, remove the cell numbers from the boxed code:
57
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Selection.Subtotal GroupBy:=2, Function:=xlSum, TotalList:=Array(3), _
Replace:=True, PageBreaks:=False, SummaryBelowData:=True
ActiveSheet.Outline.ShowLevels RowLevels:=2
Application.Run "PERSONAL.XLSB!AutoFit"
End Sub
NOTE for MacOS Users: Mac users will have a different Application.Run line
just before End Sub. On the Mac, it should be Application.Run
"'Personal Macro Workbook'.xlsb!AutoFit".
We are done with the VBA editor and our macro is now ready to be tested. Lets
close the VBA editor and test our macro.
CLICK
The VBA editor closes and we are returned to Excel. Lets save our workbook.
2. To save the workbook, on the Quick Access Toolbar,
CLICK
Our workbook is saved.
58
CONTROL
KEY+SHIFT KEY+D
NOTE for MacOS Users: To run the macro, use the View Macros dialog box from the
View tab on the Ribbon.
You see the collapsed subtotals displayed.
3. Repeat steps 2 and 3 for worksheets 2005 and 2006.
All of our data is now in good shape.
CLICK
The updated file is saved to disk.
You should now have an empty Excel workspace.
59
2. To select PERSONAL.XSLB,
ALT
KEY+F11 KEY
NOTE for MacOS Users: You can also move back to Excel from within the Visual
Basic application by pressing O PTION KEY + FN KEY +F11 KEY , or by
using the Window menu in the Menu bar to select the worksheet.
The code module that contains our code isnt open.
60
CLICK
, DOUBLE-CLICK
The code is displayed and we can see how our AutoFit macro was recorded.
5. To close the VBA editor, in the upper right corner,
CLICK
The VBA editor closes and we are returned to Excel.
Transporting PERSONAL.XLSB
Now that weve added some useful functionality to PERSONAL.XLSB, it would be
nice to be able to back it up and move it from machine to machine. This is a relatively
simple task since PERSONAL.XLSB is just a workbook stored in binary format.
The reasons behind moving PERSONAL.XLSB are simple: weve made macros that
make our work easier and it would be nice to be able to transport those macros either
to a new machine or to a machine at home or at the office so we can always use our
macros. We will be taking a look at where PERSONAL.XLSB is stored, and we will
save it to the Desktop so we can move it elsewhere from there.
61
machine and wish to use our Personal Macro Workbook on the new machine and if we
use one machine at work and another machine at home and would like all of our
macros to be in both places.
The following list explains some things to consider when moving PERSONAL.XLSB
and how to work around them:
CLICK Desktop
62
PERSONAL
4. To change the file type, in the Save as type drop-down list,
CLICK
CLICK
The Personal Macro Workbook is now saved to the desktop so we can easily
find and move the file. Lets hide the Personal Macro Workbook so next time
we open Excel, it doesnt open automatically.
6. To hide the Personal Macro Workbook, on the Ribbon,
CLICK
NOTE for MacOS Users: On the Mac, in the Menu bar, C LICK Window, C LICK
Hide.
The workbook is now hidden.
Quitting Excel
Lets go ahead and close Excel.
1. To close Excel,
CLICK
NOTE: You may need to choose Exit Excel more than once. Sometimes when you use
the Personal Macro Workbook, Excel will stay open after the first time you
tell it to close. Telling the application to close again will make it quit.
63
CLICK
You should be returned to the Desktop.
NOTE: To find more training and information about Excel, go to:
http://ittraining.iu.edu/Excel/
Wrapping Up
Weve reached the end of these materials. At IT Training, we value your opinion very
much, and want to hear your feedback about what we are doing well in these materials,
or how they might be improved.
If you are in our classroom, please follow your workshop instructors guidance and
take a few moments to fill out the workshop evaluation form. Also, before leaving,
please log off your computer.
If you are working through these materials on your own, please take a few moments to
fill out the materials evaluation form:
http://ittraining.iu.edu/eval.aspx?mat=254
Tom Mason
Author
Tom Mason
Development Team
Editor(s)
64
Erin Dunn
Susan Hanns
Veronica Mount
Sandy Doell
(IUB) 812/855-6789
(IUPUI) 317/274-4357