You are on page 1of 10

Page 1 of 10

Excel Macro
A. Overview
You do not need to know anything about Microsoft Office
Excel macros to take this course.

"One cannot learn anything so well as by experiencing it


oneself." (Albert Einstein)

Excel macros are very powerful, and by


the end of this course, you'll understand
why

Goals
After completing this course you will be able to:

• Add a macro to a workbook.

• Use loop macros to work with ranges of data.

• Customize the included VBA code examples to work with your data.

About this course


This course includes:

• Three self-paced lessons and three practice sessions for hands-on experience.

• A short test at the end of each lesson; tests are not scored.

• A Quick Reference Card you can take away from the course
Simple, powerful, and easy to customize, Excel macros can save you time and increase your productivity. Macros called loops
are especially useful for working with ranges of data. Whether you've only heard about macros or already used them in Excel,
now's the time to find out more about them.

To learn more about this course, read the overview in the center of this page or the table of contents in the left column. Then
click Next to start the first lesson.

Meet macros

What are macros? Where are they kept? Why should I care? Very good questions.
Macros in Excel are bits of code stored in the workbook that can automate
repetitive tasks and quickly get your data in order. They make life easier, and
that's why you should care.

Three key terms: macro, module, VBA.

EXCEL MACROs
Page 2 of 10

Introduction to terms

The macro code language for most Office programs, including Excel, is Visual Basic for
Applications (VBA). You may have recorded macros in Excel by stepping through actions
that the program saves for you. When you record a macro, Excel records the VBA code
describing your actions in a module attached to the workbook. Think of a module as a
container for a number of macros. Would that be easier to remember as a list of
definitions?

• macro: a bit of code that produces a specific effect and has its own name

• VBA: Visual Basic for Applications, the code language of macros

• module: a container for storing macros, attached to a workbook.

Modules are containers for storing macros, which are written in VBA.

Write macros in the Visual Basic Editor

Suppose you wanted to write a macro. First things first: You'd need to
open the Visual Basic Editor. On the Tools menu, you'd point to
Macro, and then you'd click Visual Basic Editor.

Why would this be the first thing you'd do? Because the Visual Basic
Editor is a tool for writing and editing VBA. The name kind of gives
that away.

Open the Visual Basic Editor.

To write macros, start with modules

Second things second: Before you started writing a macro, you'd need to
decide where to keep it. Remember modules? Modules are containers for
macros, attached to a workbook through a larger container called a VBA
Project.

You'd add a new module in the Visual Basic Editor by selecting Module on that
editor's Insert menu (not the spreadsheet's menu). A blank module window
would then appear inside the main window of the Visual Basic Editor.

Insert a module as a container to store macros.

EXCEL MACROs
Page 3 of 10

Give your macro a name

To actually write a macro, you'd type the word Sub in the module window.
(Why? It doesn't matter. It's just that way.) Next you'd type a space and then
the name of your macro. If you typed Sub MyMacro, for instance, you'd
create a new macro called MyMacro. Because the Visual Basic Editor is so
smart, it would automatically insert a line below your Sub line that said End
Sub — how convenient! You've got the beginning and the end, now all you
need is some code between them, in the handy new space.

Give your macro a name.

Add code to your macro

Suppose you'd followed these steps and created a macro. Because there's nothing
between your Sub line and your End Sub line, your new macro wouldn't actually
do anything. You'd need to add code to bring your macro alive. Here's an example.
Say you wanted to show a simple message. Between the Sub line and the End
Sub lines, you would type:

While MsgBox may look like a typo, this is the VBA word for a message box.
Because VBA is very literal, you must type exactly what appears above, and it's
important to include the quotation marks around the rest of the text in this line of
Code makes the macro effective. code. If you ran this macro, Excel would show a message containing My first
macro and an OK button, which would close the message. In the practice that's
coming up next, you'll get a chance to write and run this macro.

Tip. A great way to create your own code example is to record a macro for the
action first. On the Tools menu, point to Macro and select Record New Macro.
Once you've recorded the macro, take a look at it in the Visual Basic Editor to
see how its code works. On the Tools menu, point to Macro and then select
Macros to find the one you recorded. Select it and click Edit to see the code.

Practice In this practice session, you will add a new module to a workbook and then write a
macro, which will be stored inside that module.

About the practice session


When you click Practice in Excel at the bottom of this page, a practice worksheet
will download to your computer and open in Excel, and a separate window with
practice instructions will appear alongside (see picture).

Tips

• If the practice instructions aren't visible, or if they disappear when you


click in Excel, click the Excel Help taskbar button and then click the Auto Tile
button in the upper-left corner of the instructions.

• If the practice instructions cover up Excel, click the Auto Tile button in
the upper-left corner of the instructions.
Before you begin
Make sure to close Excel if it is already running.

Practice instructions appear in a Start the practice


separate window alongside Excel. EXCEL MACROs
Click the Practice in Excel button now.
Page 4 of 10

Test yourself

Where do you actually write macros?. In the Visual Basic Editor. Correct! The Visual Basic Editor is the place where macros
are written. You did that in the practice.

Where does the name of the macro appear in the code?. After the word "Sub" on the same line. Correct! The name of
the macro is on the same line as the word "Sub."

The word "Sub" is the _____ of the macro. Start. Correct!.

B. Use loop macros

Powerful macros called loops work through data,


performing actions repeatedly and automatically.
When you are dealing with large ranges of data,
or ranges of various sizes, loops can save you a
lot of time and effort.

A loop performs an action over and over again automatically.

The Do…Loop Suppose you wanted to count the number of rows in a range of data that
can sometimes be small and sometimes really big. You'd want to use a
Do…Loop. This type of loop performs an action as many times as
necessary. It would count whatever number of rows it found in the range.
Or suppose you wanted to perform one action on two ranges of data
containing different numbers of rows. Again, you'd use a Do…Loop. The
loop would run as many times as necessary for each of the two ranges.
How does the loop know what's necessary? You tell it. The loop stops
running when it meets a specific piece of data, such as a blank line or some
particular text.

You use either the While condition or the Until condition to specify when a
Do…Loop will stop. As long as something is true, or until something is
true, the loop runs. So for a loop that stops when it finds a blank cell in the
first column, you would use the While condition, as follows:

A Do…Loop counts rows in a range of data as


long as it does not find a blank row.

Here the While condition is used so that the loop runs as long as the cell
being acted on is not blank. The row being worked on is x, and (x,1) is the
first cell in that row. Used together, the signs <> mean "does not equal."
The quotation marks with nothing between them indicate a blank cell.

If you wanted the loop to run until it found a cell containing the number
365, you'd use the Until condition. Either way, you tell the loop how to
know when it's time to stop.

EXCEL MACROs
Page 5 of 10

The For Each…Next Loop


You would use the For Each…Next loop to perform an action on every cell
in a range of data. Suppose, for example, that you wanted to make the
word "OK" darker than other text everywhere in a selected range. Your
code would look like this:

"MyCell" means whatever cell the loop is working on, and "For Each" means
A For Each…Next Loop makes the word "OK" that the loop will work on all cells in the selection. If the loop finds a cell
darker than other text, everywhere in a selection. containing only the word "OK", then it makes that word darker. (The
appearance of text is controlled by the Font property, and the Bold
property means darker text.)

The Do…Loop and the For Each…Next loop are powerful in simple ways. Now we're
Nested loops going to ratchet up the complexity a bit by introducing nested loops. You use nested
loops when you need to perform an action on a range of data more than once, or
through more than one range of data. For an analogy to nested loops, think of the
Earth revolving around the Sun. One full revolution around the Sun, a year, is like the
outside loop, and one rotation of the Earth around its axis, a day, is like the inside loop
nested within the outside loop. For each year, there are 365 inside loops, and on every
January 1st, the outside loop repeats:

A loop inside a loop.


OK, so the code above wouldn't actually run in Excel, but it illustrates that for each big
loop (around the sun) there are 365 smaller loops (around Earth's axis).

Or consider a process that would actually run in Excel. Suppose you wanted to remove
duplicate rows from a worksheet. You could compare the first row with every row after
it, find any duplicates, and delete them. Then you'd compare the second row to every
row after it, and so on, and so on. The outside loop would make the process repeat for
each row. The inside loop would do the actual comparing and deleting.

In the next lesson, you'll see exactly how to make that happen.

Use the Cells property with loops

Loop macros use two different methods to bring a cell's data into their code. One is
called the Cells property, and the other is called the Range property. In VBA, it is
usually easier and more convenient to use the Cells property, because it is easier to
change the values described by that property. The Range property identifies rows and
columns using the worksheet numbers and letters, while the Cells property uses
numbers for both rows and columns. Adding +1 to those numbers moves a loop macro
conveniently from row to row and from column to column, but there is no convenient
way to move from one letter to the next in the code.

Tip You can see column numbers instead of column letters in your spreadsheet if
you prefer. On the Tools menu, click Options, and then select the General tab.
Check the "R1C1 reference style" box. If you want to change again later, clear that
check box.

Columns represented as numbers instead of letters. EXCEL MACROs


Page 6 of 10

Practice In this practice session you will copy macros into a workbook that already has some
data in it, and you'll use the macros to do some counting.

About the practice session


When you click Practice in Excel at the bottom of this page, a practice worksheet
will download to your computer and open in Excel, and a separate window with
practice instructions will appear alongside (see picture).

Tips

• If the practice instructions aren't visible, or if they disappear when you click
in Excel, click the Excel Help taskbar button and then click the Auto Tile button
in the upper-left corner of the instructions.

• If the practice instructions cover up Excel, click the Auto Tile button in the
upper-left corner of the instructions.
Before you begin
Make sure to close Excel if it is already running.

Start the practice


Click the Practice in Excel button now.
Practice instructions appear in a separate window alongside Excel.

Test yourself

If you want a loop to run until it finds a specified value, what type of loop would you use?. A Do...Loop. Correct! A
Do…Loop with a While or Until condition runs as long as a specified value is not found.

When looping through a list in Excel, is it easier to use the Cells property or the Range property?. The Cells
property. Correct! Using the Cells property, you can specify variables for rows and columns instead of trying to piece together a
range reference like "C123".

When is it best to use a Do…Loop?. When your range of data can grow or shrink, When the end of your data range is
shown by a specific value or condition, When you don't need to loop through every cell. Correct! To loop through every cell, use
a For Each…Next loop.

C. Work with code examples

You've come a long way in learning about loop macros, and VBA
macros in general. Now you're ready to try out this knowledge by
running some real code. To make that simpler, we'll give you code
you can build upon.

Try out code examples.

EXCEL MACROs
Page 7 of 10

Start with code examples


Even the best code writers like to start with an example, because

• They're lazy.

• It's easier.
We'll provide you with three different code examples that perform
actions on the data in the practice file. Once you're familiar with
these examples, you can tweak them to work with your own data.

Adopt, adapt, improve: find a code example and customize it.

A Do…Loop example combines columns

With this macro, you could combine values from two columns into a third
column, with a space between them. In the practice data, the columns to
combine are First Name, Last Name, and Full Name, as shown in the
illustration. You might be thinking "I could do this with a formula — is a macro
really necessary?" And you would be right. You can do many things in Excel
with formulas, and this process happens to be a prime candidate for a formula.
However, this example also makes clear just how a Do…Loop works and what
you can accomplish with this type of loop.

This Do…Loop macro combines two columns


into a third.

In this example, the first name and last name are copied into the Full Name
column with a space between them. This operation is performed while the value
of Cells(x,3) is not blank. The variable x is used to track the current row
number, and increasing x moves the operation to the next row. The columns
are specified by the nonvariable values of 3, 4, and 5, which represent columns
C, D, and E, respectively.

Tip Pay careful attention to the comment text in green when you are trying
to understand these VBA macros. When you are working in the Visual Basic
Editor, you can insert more comments by typing an apostrophe at the beginning
of a new line. VBA will ignore that line when it runs the macro.

EXCEL MACROs
Page 8 of 10

A For Each…Next Loop example assigns background color

With this macro, you could set the background colors of cells in a selected
range. The background will be red if a cell has the word "book" in it, green if it
has the word "movie" in it, blue if it contains any other value, and clear if the
cell is blank.

This process could be accomplished by using the Conditional Formatting


feature. However, this code example shows how to operate on all cells in a
selected range with a loop.

This For Each…Next Loop macro reads each


cell and colors it according to the contents.

"MyCell" is a variable that tracks the cell the loop is acting on. The asterisks in
the code example allow the code to find the specified text when it is part of
more text. As you see in the illustration, this code does not search only for text
starting with capital letters. It finds both "Book" and "Read the book." To obtain
this behavior, you would need to specify it before entering the macro.

At the very beginning of the module, before typing Sub or pasting any other
code, you would enter the following code:

This option specifies that any following code using the Like operator will ignore
the case of text it acts on. Without this option, the code example would change
background color only when it found text starting with a capital letter.

A nested loop example deletes duplicate rows

This nested loop macro deletes rows with duplicate values in two columns.

EXCEL MACROs
Page 9 of 10

With this macro, you could delete rows that contain duplicate values in columns D and F both. The power of this macro is that you can
adapt it to act on duplicate values in other columns in your data.

Note Take care when running this macro! It will delete data from your spreadsheet. And when you run a macro, there is no Undo.
What's done is done. To be safe, copy your data first, and run this macro on the copy to test the results.

The inside loop finds any rows that duplicate the starting row, and removes them. The outside loop moves the starting row down the
selection, one row at a time, until each row has been compared with all those below it in the selection.

Practice Now you'll add a module in a workbook, copy and paste three loop macros into it,
and run the macros to see what they do and how they do it.

About the practice session


When you click Practice in Excel at the bottom of this page, a practice worksheet
will download to your computer and open in Excel, and a separate window with
practice instructions will appear alongside (see picture).

Tips

• If the practice instructions aren't visible, or if they disappear when you


click in Excel, click the Excel Help taskbar button and then click the Auto Tile
button in the upper-left corner of the instructions.

• If the practice instructions cover up Excel, click the Auto Tile button in
the upper-left corner of the instructions.
Before you begin
Make sure to close Excel if it is already running.

Start the practice

Practice instructions appear in a separate Click the Practice in Excel button now.
window alongside Excel.

EXCEL MACROs
Page 10 of 10

Test yourself

By default, VBA is case sensitive when using the Like operator to compare text. True. Correct! Specify "Option
Compare Text" in the module if you don't want VBA to be case sensitive when comparing text.

Why is it easier to start writing a macro with a code example?. An example gives you a framework to start with, so you
don't have to write your macro from scratch, If you start with a working macro, you know that the basic logic of the macro is
OK, An example can jump start your macro.

How do you undo actions performed by a macro?. You can't, so back up your data. Correct! Especially if you're deleting
data from your spreadsheet, make sure you have a backup!.

EXCEL MACROs

You might also like