Anda di halaman 1dari 65

Excel 2016: Basic Automation

Using Macros

Windows & MacOS

Excel 2016: Basic Automation Using Macros v4.0.0

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

Copyright 2016 - The Trustees of Indiana University


These materials are for personal use only and may not be copied or distributed. If you would like to use our materials
for self-study or to teach others, please contact us at: IT Training, 2709 East 10th Street, Bloomington, IN 474082671, phone: (812) 855-7383. All rights reserved.
The names of software products referred to in these materials are claimed as trademarks of their respective companies
or trademark holders.

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

Examples of Macro Viruses . . . . . . . . . . .


Protecting Your Computer from Macro Viruses .
Recording a Second Macro . . . . . . . . . . . . . . .
Turning on Excels Recorder on Windows . . . . .
Turning on Excels Recorder on MacOS . . . . . .
Recording a Sequence of Actions . . . . . . . . . .
Sorting . . . . . . . . . . . . . . . . . . . . . .
Calculating Subtotals . . . . . . . . . . . . . . .
Finishing Recording the Macro . . . . . . . . .
Running the Macro . . . . . . . . . . . . . . . . . .
Viewing the Visual Basic Module . . . . . . . . . . . .
Overview of Visual Basic, VBA, and VBScript . . .
Opening the Visual Basic Editor . . . . . . . . . . .
Comments . . . . . . . . . . . . . . . . . . . .
Sub Statements . . . . . . . . . . . . . . . . . .
Statements . . . . . . . . . . . . . . . . . . . .
Editing a Macro . . . . . . . . . . . . . . . . . . . . .
Fixing the DataSorter Macro . . . . . . . . . . . . .
Recording a New Macro . . . . . . . . . . . . . . .
Moving Code . . . . . . . . . . . . . . . . . . . . .
Viewing Multiple Macros in a Single Module . .
Copying and Pasting the Code . . . . . . . . . .
Making a Macro Scalable . . . . . . . . . . . .
Closing the VBA Editor . . . . . . . . . . . . . . .
Testing the New Macro . . . . . . . . . . . . . . .
Saving and Closing the Open Workbook . . . . . .
Viewing the Personal Macro Workbook . . . . . . .
Transporting PERSONAL.XLSB . . . . . . . . . . . .
Using PERSONAL.XLSB on Other Machines . . .
Saving PERSONAL.XLSB to the Desktop . . . . .
Quitting Excel . . . . . . . . . . . . . . . . . . . .
Wrapping Up . . . . . . . . . . . . . . . . . . . . . . .
Contributions to These Materials . . . . . . . . . . . .

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

. 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

Welcome and Introduction


Welcome to Excel 2016: Basic Automation Using Macros.

What You Should Already Know


You should have already attended Excel 2016: The Basics or have the equivalent
skills. Specifically, you should be able to:

create, replace, and rename subtotals


enter data into cells
use built-in functions
sort and filter lists

What You Will Learn


Macros can customize Excel to easily perform complex tasks. This workshop will
introduce you to basic Excel macro concepts. Specifically, you will:

create simple macros to automate complex actions


learn about macro security issues
assign a macro and a keyboard shortcut to the Quick Access Toolbar
edit macros
make macros available to other workbooks and users

What You Will Need to Use These Materials


To complete this workshop successfully, you will be provided with:

the use of Microsoft Excel 2016


the exercise file inside the Excel Macros folder, macroex.xlsx.

Excel 2016: Basic Automation Using Macros v4.0.0

Getting Started
These materials presume you will begin work from the desktop, and have any required
exercise files located in an epclass folder there.

Getting the Exercise Files


Most of our workshops use exercise files, listed at the bottom of page 5 of the materials. In our computer-equipped classrooms, these files are located in the epclass folder,
which should already be on the computer desktop. If you are using our materials in a
different location, you may obtain the exercise files and detailed installation instructions from our Web site at:

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/

Want to Learn More?


IT Training offers many training options for extending your skills beyond this workshop:

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/

Excel 2016: Basic Automation Using Macros v4.0.0

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.

About These Materials for MacOS Users


These materials are written with the presumption that you have modified a particular
MacOS system setting for the Keyboard, which will enable many of the same keyboard shortcut combinations used by Windows to behave as expected on your MacOS
computer. Information regarding this simple change is available at:

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

C ONTROL KEY +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.

Excel 2016: Basic Automation Using Macros v4.0.0

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 Open Other Workbooks


NOTE for MacOS Users: To begin to open the file, on the menu bar, in the File menu,
C LICK Open.
3. To continue to open the 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.

Setting the Location for Opening Your File


When the dialog box opens, it lists a default location from where the file will be
opened. All of our exercise files are contained in the epclass folder, located on the
desktop. Well want to change our location to this folder.
We will start at the desktop, since our exercise file folder, epclass, is located there.

Excel 2016: Basic Automation Using Macros v4.0.0

1. To move to the desktop,

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 the Excel Macros folder


4. To open the first workshop file,

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.

Excel 2016: Basic Automation Using Macros v4.0.0

Turning on Excels Recorder for Windows


Lets begin by enabling Excels macro recorder.
1. To switch to the View tab, on the Ribbon,

CLICK the View tab


2. To access the macro commands, on the right side of the Ribbon,

CLICK

CLICK Record Macro...

You see the Record Macro dialog box:

3. To enter the macro name, type:

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

Excel 2016: Basic Automation Using Macros v4.0.0

4. To assign the key combination C ONTROL KEY +S HIFT KEY + A to the


macro, press:

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

, CLICK Personal Macro Workbook,


press: TAB

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:

A macro to automatically fit columns to their data.


We are done setting up our macro so lets begin recording.

Excel 2016: Basic Automation Using Macros v4.0.0

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.

Turning on Excels Recorder on MacOS


Lets begin by enabling Excels macro recorder.
1. To switch to the VIEW tab, on the Ribbon,

CLICK the VIEW tab


2. To access the macro commands, on the right side of the Ribbon,

CLICK
You see the Record Macro dialog box:

12

Excel 2016: Basic Automation Using Macros v4.0.0

3. To enter the macro name, type:

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

, CLICK Personal Macro Workbook,


press: TAB

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:

A macro to automatically fit columns to their data.


We are done setting up our macro so lets begin recording.
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.

Recording a Sequence of Actions


In order to record a macro that will automatically fit column widths to the data contained in that columns cells, we need to select the whole worksheet.

Selecting the Whole Worksheet


By selecting the whole worksheet, we can adjust all columns at the same time, not just
the columns that currently contain data. This allows us to expand our worksheet without rewriting our macro. This is a concept known as scalability. Scalability is the ability of a system to handle expansion without having to redesign core functionality.

Excel 2016: Basic Automation Using Macros v4.0.0

13

1. To select the entire worksheet,

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.

Finishing Recording the Macro


We will finish the macro by leaving cell A1 as the active cell.
1. To stop the recorder, on the left side of the status bar,

CLICK
The actions have been recorded as the content of the AutoFit macro.

14

Excel 2016: Basic Automation Using Macros v4.0.0

Running the Macro


Macros can be run in several different ways. They can be launched from the Macro
dialog box or by using a key combination. Macros can also be assigned to a button on
the Quick Access Toolbar. We will explore each of these approaches in this workshop.

Using the Macro Dialog Box


Lets first see how to run the macro we created from the Macro dialog box.
1. To select the next sheet,

CLICK the 2004 worksheet tab


The 2004 worksheet appears.
2. To access the macro commands, on the right side of the Ribbon,

CLICK

CLICK View Macros

The Macro dialog box appears.


NOTE for MacOS Users: On the Mac, in the View tab, C LICK

3. To run the AutoFit macro, in the Macro dialog box,

CLICK PERSONAL.XLSB!AutoFit, CLICK


NOTE for MacOS Users: C LICK Personal Macro Workbook!AutoFit, C LICK
We see that the columns all fit to their data, just like what we recorded.
NOTE: The prefix PERSONAL.XLSB! tells us that the macro is stored in the Personal
Macro Workbook.

Using the Control Key


On Windows, we assigned the C ONTROL KEY + S HIFT KEY + A key combination
to the macro when we created it.
Lets see how to run the macro using this key combination.
Excel 2016: Basic Automation Using Macros v4.0.0

15

1. To run the macro in the 2005 worksheet,

CLICK the 2005 worksheet tab


The 2005 worksheet appears.
2. To start the macro from the keyboard, press:

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.

Adding a Macro to the Quick Access Toolbar


If a macro is to be used often, adding it to the Quick Access Toolbar will make access
easy.

Adding a Macro to the Quick Access Toolbar on Windows


1. To begin customizing the Quick Access Toolbar,

CLICK File, CLICK


You see the Excel Options dialog box.

16

Excel 2016: Basic Automation Using Macros v4.0.0

2. To customize the Quick Access Toolbar, in the navigation pane,

CLICK Quick Access Toolbar


You see the Excel Options dialog box:

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.

Excel 2016: Basic Automation Using Macros v4.0.0

17

3. To find macros in the choose commands from drop-down list on the left,

CLICK

, CLICK Macros

We see a list of all our macros.


We would like to separate the macros section of our Quick Access Toolbar from
the standard office commands for the sake of organization. This can be accomplished by inserting a <Separator> at the beginning of the macro toolbar items.
4. To insert the <Separator>, in the Choose command from: column,

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.

Changing the Icon and Name of a Button


Once a command is added to the Quick Access Toolbar, we can modify the way it
looks and the caption it displays when the mouse hovers over it.
1. To begin modifying the AutoFit button, in the right column,

CLICK PERSONAL.XLSB!AutoFit
The AutoFit macro is selected.

18

Excel 2016: Basic Automation Using Macros v4.0.0

2. To open the modify menu, below the right column,

CLICK
You see the Modify Button dialog box:

3. To change the display icon,

CLICK any icon


4. To select the current display name, in the Display Name field,

PRESS & DRAG the current value


5. To change the display name, type:

Auto Fit
6. To make the change,

CLICK
We are returned to the Customize window.

Excel 2016: Basic Automation Using Macros v4.0.0

19

7. To close the Customize window,

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.

Adding a Macro to the Quick Access Toolbar on MacOS


1. To begin customizing the Quick Access Toolbar, in the Menu bar,

CLICK Excel, CLICK Preferences


You see the Preferences dialog box.

20

Excel 2016: Basic Automation Using Macros v4.0.0

2. To customize the Quick Access Toolbar,

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.

Excel 2016: Basic Automation Using Macros v4.0.0

21

3. To customize the Quick Access Toolbar, find macros in the choose commands
from drop-down list on the left,

CLICK

, CLICK Macros

We see a list of all our macros.


4. To add AutoFit to the Quick Access Toolbar, in the left column,

CLICK Personal Macro Workbook!AutoFit


, CLICK SAVE, Close the Window
CLICK
AutoFit is now added to the Quick Access Toolbar. Lets explore modifying it
further.

Changing the Name of a Button for Macs


1. To rename an item on the Quick Access Toolbar, in the right window of the
Ribbon & Toolbar dialog box

CLICK Personal Macro Workbook!AutoFit, CLICK


A drop-down menu opens.
2. To open the rename the button,

CLICK Rename, type: Auto Fit, CLICK Save


The tool has been renamed.
3. Close the Preferences window.

Using the Quick Access Toolbar to Run a Macro


We can use the new Auto Fit button to format a sheet in one simple step.
1. To select the 2006 worksheet,

CLICK the 2006 worksheet tab


The 2006 worksheet appears.

22

Excel 2016: Basic Automation Using Macros v4.0.0

2. To run the macro, on the Quick Access Toolbar,

CLICK the Auto Fit button


The columns are widened with just a single click of the mouse. Lets save our
work.
3. To save the workbook, on the Quick Access Toolbar,

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.

Using an Auto_Open Macro on Windows


Not only can a macro be run by keyboard shortcuts, the macro menu, or a button on
the Quick Access Toolbar, Excel also allows you to run a macro automatically when a
workbook opens. These types of macros are called Auto_Open macros.
In order to make our AutoFit macro an Auto_Open macro, we need to record it again,
but name it Auto_Open.
1. To begin recording a macro, on the Status Bar,

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.

Excel 2016: Basic Automation Using Macros v4.0.0

23

3. If necessary, to select This Workbook and move to the description field, press:

CLICK

, CLICK This Workbook, press: TAB

KEY

Lets add a description to this macro.


4. To enter a description of the macro, type:

A macro to automatically fit columns to their data when


a workbook is opened
5. To begin recording the macro,

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

Excel 2016: Basic Automation Using Macros v4.0.0

Using an Auto_Open Macro on MacOS


Auto_Open macros can be used in Excel 2016 for Mac, but you cannot record running
a macro using the macro recorder in Excel for Mac. Instead, you have to manually add
the code that runs the macro. Lets create an Auto_Open macro, then add the appropriate code to make our macro automatically fit columns when a workbook is opened.
1. To begin recording a macro, on the Status Bar,

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

Store macro in:

This Workbook

Description

A macro to automatically fit columns to their


data when a workbook is opened

3. To begin recording the macro,

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.

Excel 2016: Basic Automation Using Macros v4.0.0

25

5. To edit the macro, in the Ribbon,

CLICK the View tab, CLICK


CLICK Auto_Open, CLICK

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

The Application.Run command allows us to run a macro by name. The


macro name must be in quotation marks. The workbook name (Personal Macro
Workbook) has apostrophes around it here because it has spaces in its filename.
We can now close the Visual Basic Editor and return to our workbook.
7. Close the Visual Basic Editor.
NOTE: Alternatively, you can use the Window menu in the Menu bar to switch back
to the workbook and leave the Visual Basic Editor open.

Saving the Workbook


Now that we have recorded our Auto_Open macro, it is time for testing. We must first
modify some of the column widths so we can see if the macro works or not, then save
and close the workbook and reopen it to see the effects of our macro.
Lets change some column widths first.

26

Excel 2016: Basic Automation Using Macros v4.0.0

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:

3. To save the file as a macro-enabled workbook,

CLICK

, CLICK Current Folder (Excel Macros)

NOTE for MacOS Users: On the Mac, C LICK


We see the Save As dialog box.

Excel 2016: Basic Automation Using Macros v4.0.0

27

Understanding File Formats in Excel 2016


The Excel 2016 default format (xlsx) preserves all worksheet and chart data, formatting, and other features available in Excel 2016. In addition to these features, the
macro-enabled workbook format (.xlsm) preserves macros and macro sheets. The
Excel Binary file format (*.xlsb) can be used for optimal performance and backward
compatibility for large or complex workbooks.
We will be saving our workbook as a macro-enabled workbook (*.xlsm).
1. To change the file format, in the Save As Type text box,

CLICK

, CLICK Excel Macro-Enabled Workbook


(*.xlsm)

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

Our file is now saved as a macro-enabled workbook (*.xlsm).


3. To close the workbook,

CLICK File, CLICK Close


We see an empty Excel work space.
NOTE for MacOS Users: On the Mac, the Excel Workspace is transparent when its
empty.
4. To re-open the workbook,

CLICK File, CLICK Open


We see the Open File dialog box.
5. If necessary, navigate to the epclass folder.

28

Excel 2016: Basic Automation Using Macros v4.0.0

6. To open the file,

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:

Nothing has happened because, by default, macro-enabled workbooks open


with all macro content disabled. The security warning will allow us to enable
this content.

Understanding Macro Security


Macros are disabled by default because they can be vectors for malicious code such as
viruses or other exploits. Excel protects the end user from these harmful pieces of code
by disabling the questionable content altogether when a macro-enabled workbook is
opened.
The disabling of macro content does not affect the ability to edit data; it just affects
running macros on the data. In Office 2016, data is always available even if macro
content is disabled.
We will discuss macro security settings later, but for now, lets go ahead and enable
this content and continue.

Excel 2016: Basic Automation Using Macros v4.0.0

29

1. To enable the macro content,

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.

Using the Trust Center


Macro security in Office 2016 is controlled by a group of settings called the Trust
Center. The Trust Center allows us as an end user to specify who we trust as publishers and which directories contain trusted files. When opening a file in a trusted location or from a trusted source, Excel will not disable any content and will not even
prompt to have the content disabled.
On the Mac, Office 2016 applications have been sand-boxed, which means that Excel
is restricted from accessing resources outside the application container. For more
information about macros security for Office 2016 on the Mac, visit,

https://msdn.microsoft.com/en-us/library/mt654019.aspx

Setting Trusted Locations on Windows


We will begin by making the folder a trusted location.
1. To open Excel Options,

CLICK File, CLICK


You see the Excel Options dialog box.

30

Excel 2016: Basic Automation Using Macros v4.0.0

2. To access the Trust Center, in the navigation pane,

CLICK Trust Center


You see:

This window contains a list of links to resources Microsoft provides to explain


their stance on user privacy as well as some resources to help keep yourself safe
online. We are interested in the bottom section of this page titled Microsoft Office Excel Trust Center.
By default, these settings are set to a pretty high level of security. We will be
lowering security for the Excel Macros folder because we trust all the content
in this folder since we created it.
NOTE: Remember, when a location is designated as a trusted location, any content in
this folder will bypass the built-in security features in Microsoft Office 2016.
For this reason, folders should only be marked as trusted after careful consideration.
Lets take a look at the Trust Center Settings.

Excel 2016: Basic Automation Using Macros v4.0.0

31

3. To view the Trust Center Settings,

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

Excel 2016: Basic Automation Using Macros v4.0.0

each section:
Section

Description

Trusted Publishers

Trusted publishers are developers who


create macro, ActiveX, or add-in content
for Excel. Content from trusted publishers
will be signed with a valid digital signature.
For more information see Excels online
help.

Trusted Locations

Trusted locations are folders on your hard


drive or any network drive where you place
content you know to be from a trusted
source. Any file placed in a trusted location
will be opened without being checked by
the Trust Center.

Trusted Documents

Trusted documents are documents that


have been opened previously and their
macro content was enabled. If you opened
a document in error, you can clear the list
here.

Trusted App
Catalog

Trusted app catalogs are trusted locations


on a SharePoint site. Use the settings in
this section to identify catalogs that contain
only documents from trusted sources.

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

ActiveX Settings allow the user to set how


he/she would like the application to handle
ActiveX controls.

Macro Settings

Macro settings allow the user to designate


which macros should be enabled by default
in certain files.

Protected View

Allows files from potentially unsafe locations to be opened, inspected, and reviewed while minimizing risk to your
machine.

Excel 2016: Basic Automation Using Macros v4.0.0

33

Section

Description

Message Bar

Message Bar determines whether or not


the Message Bar is shown when questionable content is present.

External Content

External Content controls how Excel handles connections to external data or external workbooks.

File Block Settings

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.

We will be working today with Trusted Locations. For more information on


each of the sections of the Trust Center, please refer to the Microsoft Office Online Help.
4. To view the Trusted Locations settings, in the navigation pane,

CLICK Trusted Locations


We see the folders that are already defined as Trusted Locations.

34

Excel 2016: Basic Automation Using Macros v4.0.0

5. To begin adding a new location,

CLICK
You see:

6. To select the folder,

CLICK
We see the Browse dialog box.
7. Navigate to the epclass folder.
8. To select the subfolder,

CLICK Excel Macros, CLICK


We can also designate whether or not we want to implicitly trust the subfolders
of our new location. We will allow folders inside this trusted location to be
trusted as well.
9. To implicitly trust the subfolders of Excel Macros,

CLICK the Subfolders of this location are also trusted


checkbox
Lets add a description to this location.

Excel 2016: Basic Automation Using Macros v4.0.0

35

10. To select the description field, press:

TAB

KEY

11. To add a description, in the Description field, type:

This location stores the files used in Excel 2016: Basic


Automation Using Macros
We are done modifying this location.
12. To finish adding the new location,

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

You should be back in the macroex.xlsm workbook.

Testing the Trust Center Settings


Now that weve added a trusted location, lets explore the effect this has on opening
files. We will first close our file, then re-open it from the trusted location. We will also
narrow some columns so we can verify that our auto_open macro runs when our file
opens.
1. Resize a few columns.
2. Save and close the workbook.
3. To open the workbook,

CLICK File, CLICK Open, DOUBLE-CLICK macroex.xlsm


We see that our workbook opens without a security warning and that our macro
has resized our columns as needed.

36

Excel 2016: Basic Automation Using Macros v4.0.0

Setting Security and Privacy on MacOS


1. To review the security and privacy settings on the Mac,

CLICK Excel, CLICK Preferences


You see the Preferences dialog box
2. To see Security and Privacy settings,

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

Best Practices in Macro Security


We have been discussing how to protect our machines from malicious macro code, but
what makes macro code malicious and what are some behaviors that can minimize the
risk of being victimized by a macro?

Examples of Macro Viruses


The first Excel macro virus was called ExcelMacro/Laroux, or Laroux for short. It
consisted of an auto_open macro and a macro called check_files. When the workbook
was opened, it would look for an occurrence of the Personal Macro Workbook. If none

Excel 2016: Basic Automation Using Macros v4.0.0

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.

Protecting Your Computer from Macro Viruses


There are a few behaviors that can be modified to better protect yourself from malicious macros.
The following list outlines these behaviors in more detail.

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

Excel 2016: Basic Automation Using Macros v4.0.0

For more information about macro security, visit the following link to the Knowledge
Base:

http://kb.iu.edu/data/agzl.html

Recording a Second Macro


We will now record a second, more complex, macro to showcase some of the power
behind Excels macro interface. The macro we work with will take the data in our
workbook, sort it into categories, and provide us subtotals based on our expense type.
This type of information is helpful when determining what areas of our business could
become more cost effective. At the end of every year, we will be compiling this information and placing it in a workbook file. Our current workbook contains information
from years 2003-2006. In the future, we might put this information in a separate workbook just to keep things more organized.
We will begin our recording on the 2003 worksheet.
1. To select the 2003 worksheet,

CLICK the 2003 worksheet tab


The 2003 worksheet appears.

Turning on Excels Recorder on Windows


Lets begin by enabling Excels macro recorder.
1. To turn on the macro recorder, in the status bar,

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.

Excel 2016: Basic Automation Using Macros v4.0.0

39

3. If necessary, to select This Workbook and move to the description field,

CLICK

, CLICK This Workbook, press: TAB

KEY

Lets add a description.


4. To assign the key combination C ONTROL KEY +S HIFT KEY + D to the
macro, press:

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:

A macro to sort data and return subtotals by Expense


type
We are ready to begin recording.
6. To begin recording,

CLICK
Lets take a look at the actions we will record.

Turning on Excels Recorder on MacOS


Lets begin by enabling Excels macro recorder.
1. To turn on the macro recorder, in the status bar,

CLICK
We see the Record Macro dialog box.

40

Excel 2016: Basic Automation Using Macros v4.0.0

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

Store macro in:

This Workbook

Description

A macro to sort data and return subtotals by


Expense type

3. To begin recording,

CLICK
Lets take a look at the actions we will record.

Recording a Sequence of Actions


Our data may or may not be the same size on each workbook, so we will be working to
make this macro as scalable as possible. Unfortunately for us, we wont be able to
make our data flexible using just a macro; we will have to enter the Visual Basic
Editor to slightly modify the code Excel generates when we are finished recording.

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,

CLICK cell A10


We didnt need to select the whole range because Excel will automatically select all adjacent cells that contain data.
2. To select the Data tab, on the Ribbon,

CLICK the Data tab

Excel 2016: Basic Automation Using Macros v4.0.0

41

3. To select the Sort command, on the Ribbon,

CLICK
NOTE for MacOS Users: On the Mac, C LICK
You see the Sort window:

4. To change the Sort by option to Expense, on the Sort by drop-down list,

CLICK

, CLICK Expense

This is our only sort criteria.


5. To complete the sorting process,

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

Excel 2016: Basic Automation Using Macros v4.0.0

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.

Excel 2016: Basic Automation Using Macros v4.0.0

43

2. Change the dialog box settings shown below:


Field

Change to:

At each Change in:

Expense

Use Function

Sum

Add Subtotal to:

Amount

The Subtotal dialog box should look like:

3. To confirm these settings as correct,

CLICK
We see that our data is sorted by expense type and each expense group has its
own subtotal.

Finishing Recording the Macro


We will finish the macro by leaving cell A10 as the active cell.

44

Excel 2016: Basic Automation Using Macros v4.0.0

1. To stop the recorder, in the status bar,

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.

Running the Macro


We saw earlier the multiple ways to run a macro. For this exercise, we will simply use
the keyboard shortcut to sort and subtotal our data.
1. To sort the 2004 worksheet,

CLICK the 2004 worksheet tab


The 2004 worksheet appears.
2. To run the macro, press:

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.

Excel 2016: Basic Automation Using Macros v4.0.0

45

3. To acknowledge the error and stop the macro,

CLICK
We now see a Visual Basic runtime error message:

4. To bypass this error,

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.

Viewing the Visual Basic Module


Macros are recorded in a programming language called Visual Basic for Applications
(VBA). VBA is very similar to the programming language Visual Basic. Recall that
Excel translates recorded actions into VBA.

Overview of Visual Basic, VBA, and VBScript


The distinction between Visual Basic and Visual Basic for Applications (VBA) has
caused some confusion for programmers. There are three major Visual Basic programming products that can be purchased: Visual Basic, Visual Basic for Applications
(VBA), and Visual Basic Script (VBScript). All three languages use similar commands and syntax, but each serves a different functional purpose.
Visual Basic is for developing stand-alone programs, while VBA is the programming
language in the Office suite of programs (Excel, Access, Word etc.). It is pseudo-compiled, meaning that it cannot be used to create separate, stand-alone programs. VBA
46

Excel 2016: Basic Automation Using Macros v4.0.0

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.

Opening the Visual Basic Editor


The Visual Basic Editor can be enabled through the Macro dialog box on the View
tab.
1. To switch to the View tab, on the Ribbon,

CLICK the View tab


2. To access the macro commands, on the Ribbon,

CLICK

CLICK View Macros

NOTE for MacOS Users: On the Mac, C LICK


We see a list of all our macros.
3. Ensure that the DataSorter macro is highlighted in the dialog box.

Excel 2016: Basic Automation Using Macros v4.0.0

47

4. To edit the DataSorter macro, in the dialog box,

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

Excel 2016: Basic Automation Using Macros v4.0.0

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.

Excel 2016: Basic Automation Using Macros v4.0.0

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.

Fixing the DataSorter Macro


Although we dont know Visual Basic for Applications, we can make some simple
changes to our macro to keep it from resetting the 2003 worksheet every time we run
the macro. After examining the code we just recorded, we see that a worksheet can be
referred to as ActiveWorksheet as well as by its longer name (ActiveWorkbook.Worksheets("sheet_name")). Our DataSorter macro refers to the 2003
sheet by name:
ActiveWorkbook.Worksheets("2003")

We can solve our current problem by replacing this code with:


ActiveSheet

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,

PRESS & DRAG the first occurrence of


ActiveWorkbook.Worksheets("2003")
2. To replace the code, type:

ActiveSheet

50

Excel 2016: Basic Automation Using Macros v4.0.0

3. Repeat steps 1 and 2 every time the problematic code appears:

Any macro can be edited in the Visual Basic window or by copying and pasting
code from another macro.
4. Save the document.

Recording a New Macro


Looking back at our workbook, it would be nice if we could make our macro only
show us the subtotals for each category. We didnt think of this while we were recording our macro, so we have to add code to what Excel already created for us.
Since we havent learned to program in Visual Basic for Applications, we will generate additional code by recording a macro. We will then add that code to our current
macro by copying and pasting the recorded code.

Excel 2016: Basic Automation Using Macros v4.0.0

51

1. To return to Excel, on the toolbar,

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 the 2003 worksheet tab


The 2003 worksheet appears.
3. To begin recording a new macro, in the Status bar,

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 This Workbook

We dont need a description for this macro because it is only temporary. As


soon as we move the code out of it, we will delete the macro.
5. To begin recording,

CLICK
The recorder console appears on the worksheet, and the status bar displays the
word Recording, indicating that Excel is recording your actions.

52

Excel 2016: Basic Automation Using Macros v4.0.0

6. To reveal only the subtotals, at the top left of the worksheet,

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.

Excel 2016: Basic Automation Using Macros v4.0.0

53

1. To return to the module, press:

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.

Viewing Multiple Macros in a Single Module


All macros in this workbook are shown in this Module 1 sheet. There can be one or
more module sheets, each containing one or more macros or functions, and additional
module sheets can be created and added to a worksheet. The main reason for using
multiple modules is to help you keep things organized.
We will need only the Module1 sheet for our workbook macros. Since it is the only
Module sheet we are using, all our macros are automatically recorded into this module.
This could get a little unwieldy if we had a lot of macros in this one module, so its
useful to know how to easily move from one macro to another in a Module window.

Using the Procedure Drop-Down List


The Procedure text field and drop-down list are located in the top right corner of the
Visual Basic window. Different parts of a Module window can be displayed from the
drop-down list
NOTE for MacOS Users: The Procedure Drop-Down list does not exist on the Mac.
.

The Procedure Drop-Down List:

54

Excel 2016: Basic Automation Using Macros v4.0.0

1. To see the different components of this module window,

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#

The cursor moves into Macro#.


NOTE: In a small module like this, you can move to different macros by scrolling and
clicking, but the drop-down list is another good way to move to any macro
you want, especially in a long module with many macros.

Copying and Pasting the Code


Now that weve seen how to move from one macro to another, lets copy and paste the
code we just recorded into the DataSorter macro.
1. To select the code to copy, in Macro#,

PRESS & DRAG the uncommented code


2. To copy the selected code, press:

CONTROL

KEY+C

3. To position the cursor,

CLICK to the left of the EndSub statement at the end of


the DataSorter macro
Lets create a new line.
Excel 2016: Basic Automation Using Macros v4.0.0

55

4. To create space for the code, press:

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,

PRESS & DRAG from Sub Macro#() to End Sub


7. To delete the excess code, press:

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.

Making a Macro Scalable


Scalability is a term used to describe how a chunk of code handles differing amounts
of data. Currently, our macro will only work with values in the cells 11 - 256. If our
data were to expand, any values outside cell 256 would not be included when our
macro runs. The fix to this is simple, we will remove the cell number references in the
code but keep the letters. For example, range A10:D256 would become A:D. This
allows our code to extend past cell 256 and still be included when the macro is executed.
There are only two spots where the code needs to be changed; the range B11:B256
needs to be B:B and the range A11:D256 needs to become A:D.
Lets make these changes now.

56

Excel 2016: Basic Automation Using Macros v4.0.0

1. To make the changes, remove the cell numbers from the boxed code:

When youre finished, the DataSorter Macro should read:


Sub DataSorter()
'
' DataSorter Macro
' A Macro to sort data and return subtotals by Expense type
'
' Keyboard Shortcut: Ctrl+Shift+d
'
Range("A10").Select
ActiveSheet.Sort.SortFields.Clear
ActiveSheet.Sort.SortFields.Add Key:=Range("B:B") _
, SortOn:=xlSortOnValues, Order:=xlAscending,
DataOption:=xlSortNormal
With ActiveSheet.Sort
.SetRange Range("A:D")
.Header = xlYes
.MatchCase = False

Excel 2016: Basic Automation Using Macros v4.0.0

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.

Closing the VBA Editor


We dont have to save the work weve done in the VBA editor because it is stored in
the Excel workbook. As long as we save the workbook, our macro work will be saved.
1. To close the VBA editor, in the upper right corner,

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.

Testing the New Macro


Now that we have revised the DataSorter macro, lets test it.
1. To test the modified macro on the 2004 Sheet, at the bottom of the workbook,

CLICK the 2004 worksheet tab


The 2004 worksheet appears.

58

Excel 2016: Basic Automation Using Macros v4.0.0

2. To run the macro from the command key, press:

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.

Saving and Closing the Open Workbook


We are finished working with the two workbooks we have open, so lets save any
changes and close them.
1. To close the workbook,

CLICK File, CLICK Close


You see a dialog box asking if you want to Save changes to
macroex.xlsm.
2. To save the workbook,

CLICK
The updated file is saved to disk.
You should now have an empty Excel workspace.

Viewing the Personal Macro Workbook


The Personal Macro Workbook, by default, is hidden. To view the contents of the
workbook, we need to unhide it.

Excel 2016: Basic Automation Using Macros v4.0.0

59

1. To unhide the Personal Macro Workbook,

CLICK the VIEW tab, CLICK


NOTE for MacOS Users: On the Mac, C LICK the Window tab, C LICK Unhide
You see:

2. To select PERSONAL.XSLB,

CLICK PERSONAL.XLSB, CLICK


NOTE for MacOS Users: On the Mac, this workbooks name is Personal Macro
Workbook.xlsb
The Personal Macro Workbook is now shown.
3. To see the macros weve recorded in the workbook, press:

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

Excel 2016: Basic Automation Using Macros v4.0.0

4. To open the module, in the left sidebar,

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.

Using PERSONAL.XLSB on Other Machines


There are a few things that should be considered when transporting your copy of PERSONAL.XLSB from one machine to another. The main reasons we would want to
transport our PERSONAL.XLSB to another machine are if we were to purchase a new

Excel 2016: Basic Automation Using Macros v4.0.0

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:

Permanent vs. Temporary UseAre the macros in PERSONAL.XLSB intended to


be permanent additions to the new environment? If the macros are intended to only
be used for a short period of time, it is easier to just open the workbook youre moving
and run macros from there. If they are intended to be permanent additions, PERSONAL.XLSB should be moved into the XLSTART directory on the new machine.
Overwriting an already existing PERSONAL.XLSBDoes the machine you are
moving PERSONAL.XLSB to already have and use PERSONAL.XLSB? If so, it
would be best to open the machines current PERSONAL.XLSB and the one you are
moving and copy the macro code from the new workbook to the old workbook. This
way the old macros are preserved while adding the functionality of the new macros.
Macros with the same namesIf you are copying and pasting the code from one
PERSONAL.XLSB to another, the macros being moved need to have names that are
unique. If an old macro and a new macro share a name, both macros become nonfunctional since Excel cant tell which macro to run. A simple change like adding a
prefix or suffix to the new macro names (i.e. AutoFit-n vs. AutoFit) will solve this
problem.
Keyboard shortcutsBecause of the way keyboard shortcuts are associated with
macros, any keyboard shortcuts associated with copied and pasted macros may no
longer work. If this is the case, the macro needs to be added to the Quick Access Toolbar, or it needs to be run from the Macro menu.
Most of these issues can only be resolved by editing code in the Visual Basic Editor;
however, the modifications are simple and shouldnt cause too much of a headache.

Saving PERSONAL.XLSB to the Desktop


While we have PERSONAL.XLSB open, we will save it to the Desktop.
1. To save PERSONAL.XLSB to the Desktop,

CLICK File, CLICK Save As


The Save As dialog box appears.
2. To change the files location, in the left Favorite Links bar,

CLICK Desktop

62

Excel 2016: Basic Automation Using Macros v4.0.0

3. To name the file, in the File name field, type:

PERSONAL
4. To change the file type, in the Save as type drop-down list,

CLICK

, CLICK Excel Binary Workbook (*.xlsb)

5. To finish saving the file,

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.

Excel 2016: Basic Automation Using Macros v4.0.0

63

2. If you are prompted to save the Personal Macro Workbook,

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

Thank you for participating in

Excel 2016: Basic Automation Using Macros

Contributions to These Materials


Project Leaders

Tom Mason

Author

Tom Mason

Development Team

Editor(s)

64

Erin Dunn
Susan Hanns
Veronica Mount
Sandy Doell

Excel 2016: Basic Automation Using Macros v4.0.0

Where to Go From Here


You can use the resources listed below to further build your computing skills.

Taking Other IT Training Workshops


UITS IT Training offers hands-on instructor-led computing workshops aimed
at a variety of skill levels, covering a broad range of topics. We teach hundreds
of workshops on more than 80 topics every year! For more information, to see
a detailed workshop schedule, or to register for a workshop, contact IT Training:
Web: http://ittraining.iu.edu/
Email: ittraining@iu.edu
Phone: (IUB) 812/855-7383; (IUPUI) 317/274-7383

Getting Help from Online Resources


University Information Technology Services IU technology resources,
services and support: http://uits.iu.edu/
IT Training Online Self-paced IT courses you can take on your computer:
http://ittraining.iu.edu/online/
UITS Knowledge Base Searchable database of computing questions:
http://kb.iu.edu/
IT Training Tips Comment-enabled blog with training articles and videos:
http://ittrainingtips.iu.edu/

Getting Help from Support Staff


Walk-in Support (All IU Campuses) Walk-in Support Center. Locations and
schedules at: http://kb.iu.edu/data/abxl.html
(IUB & IUPUI) Consultants in the UITS Student Technology Centers
24 Hour Phone Support

(IUB) 812/855-6789

E-mail Support (All IU campuses) ithelp@iu.edu

(IUPUI) 317/274-4357

Anda mungkin juga menyukai