Excel® Macros For Dummies®

To view this book's Cheat Sheet, simply go to www.dummies.com and search for “Excel Macros For Dummies Cheat Sheet” in the Search box.

Introduction

In its broadest sense, a macro is a sequence of instructions that automates some aspect of Excel so that you can work more efficiently and with fewer errors. You might create a macro, for example, to format and print a month-end sales report. After you develop the macro, you can execute it to perform many time-consuming procedures automatically.

Macros are written in VBA, which stands for Visual Basic for Applications. VBA is a programming language developed by Microsoft and a tool used to develop programs that control Excel.

Excel programming terminology can be a bit confusing. For example, VBA is a programming language but also serves as a macro language. What do you call something written in VBA and executed in Excel? Is it a macro or is it a program? Excel’s Help system often refers to VBA procedures as macros, so this is the terminology used in this book.

You’ll also see the term automate throughout this book. This word means that a series of steps are completed automatically. For example, if you write a macro that adds color to some cells, prints the worksheet, and then removes the color, you have automated those three steps.

You’re probably aware that people use Excel for thousands of different tasks. Here are just a few examples:

  • Keeping lists of things, such as customer names and transactions
  • Budgeting and forecasting
  • Analyzing scientific data
  • Creating invoices and other forms
  • Developing charts from data

The list could go on and on. The point is simply that Excel is used for a wide variety of tasks, and everyone reading this book has different needs and expectations regarding Excel. One thing most readers have in common, however, is the need to automate some aspect of Excel, which is what macros (and this book) are all about.

About This Book

This book approaches the topic of Excel macros with the recognition that programming VBA takes time and practice — time that you may not have right now. In fact, many analysts don’t have the luxury of taking a few weeks to become expert at VBA. So instead of the same general overview of VBA topics, this book provides some of the most commonly used real-world Excel macros.

Each section in the book outlines a common problem and provides an Excel macro to solve the problem — along with a detailed explanation of how the macro works and where to use it.

Each section presents the following:

  • The problem
  • The macro solution
  • How the macro works

After reading each section, you'll be able to

  • Immediately implement the required Excel macro
  • Understand how the macro works
  • Reuse the macro in other workbooks or with other macros

The macros in this book are designed to get you up and running with VBA in the quickest way possible. Each macro tackles a common task that benefits from automation. The idea here is to learn through application. This book is designed so that you can implement the macro while getting a clear understanding of what the macro does and how it works.

Foolish Assumptions

I make three assumptions about you as the reader:

Icons Used in This Book

Tip icons cover tricks or techniques related to the current discussion.

Remember icons indicate notes or asides that are important to keep in mind.

Warning icons hold critical information about pitfalls you will want to avoid.

Beyond the Book

In addition to the material in the print or e-book you’re reading, this product comes with more online goodies:

Where to Go from Here

If you’re completely new to Excel macros, start with Part 1 (Chapters 1 – 3) to get the fundamentals you’ll need to leverage the macros in this book. There, you will gain a concise understanding of how macros and VBA work, along with the basic foundation you need to implement the macros provided in this book.

If you’ve got some macro experience and want to dive right into the macro examples, feel free to peruse Chapters 4 – 9 and search for the task or macro that looks interesting to you. Don’t worry. Each macro example stands on its own within its own section that gives you all the guidance you need to understand and implement the code in your own workbook.

Visit Part 2 if you’re interested in macros that automate common workbook and worksheet tasks to save time and gain efficiencies.

Explore Part 3 to find macros that navigate ranges, format cells, and manipulate the data in your workbooks.

If you want to find macros that work with PivotTables, charts, and emails, thumb through the macros in Part 4 where you will discover macros that automate redundant PivotTable and chart tasks, as well as macros that send emails and connect to external data sources.

Don’t forget to hit Part 5 for some useful tips and advice on how to get the most out of your new macro skills.

Here are some final things to keep in mind while working with the macros in this book:

Part 1

Holy Macro Batman!

IN THIS PART …

Build a foundation for your macro skills with fundamental macro recording concepts.

Get a solid understanding of the ground rules for using and distributing macros in Excel.

Explore Excel’s coding environment with a deep-dive of the Visual Basic Editor.

Explore how to leverage the Excel object model to start writing your own macros from scratch.

Understand the roles played by variables, events, and error handling in macro development.

Chapter 1

Macro Fundamentals

IN THIS CHAPTER

Why use macros

Recording macros

Understanding macro security

Examples of macros in action

A macro is essentially a set of instructions or code that you create to tell Excel to execute any number of actions. In Excel, macros can be written or recorded. The key word here is recorded.

Recording a macro is like programming a phone number into your cell phone. You first manually dial and save a number. Then when you want, you can redial those numbers with the touch of a button. Just as on a cell phone, you can record your actions in Excel while you perform them. While you record, Excel gets busy in the background, translating your keystrokes and mouse clicks to written code (also known as Visual Basic for Applications (VBA)). After a macro is recorded, you can play back those actions anytime you want.

In this chapter, you’ll explore macros and learn how you can use macros to automate your recurring processes to simplify your life.

Why Use a Macro?

The first step in using macros is admitting you have a problem. Actually, you may have several problems:

Macro Recording Basics

To start recording your first macro, you need to first find the Macro Recorder, which is on the Developer tab. Unfortunately, Excel comes out of the box with the Developer tab hidden — you may not see it on your version of Excel at first. If you plan to work with VBA macros, you'll want to make sure that the Developer tab is visible. To display this tab

  1. Choose File ⇒   Excel Options.
  2. In the Excel Options dialog box, select Customize Ribbon.
  3. In the list box on the right, place a check mark next to Developer.
  4. Click OK to return to Excel.

Now that you have the Developer tab showing in the Excel Ribbon, you can start up the Macro Recorder by selecting Record Macro from the Developer tab. This activates the Record Macro dialog box, as shown in Figure 1-1.

FIGURE 1-1: The Record Macro dialog box.

Here are the four parts of the Record Macro dialog box:

With the Record Macro dialog box open, follow these steps to create a simple macro that enters your name into a worksheet cell:

  1. Enter a new single-word name for the macro to replace the default Macro1 name.

    A good name for this example is MyName.

  2. Assign this macro to the shortcut key Ctrl+Shift+N.

    You do this by entering uppercase N in the edit box labeled Shortcut Key.

  3. Click OK.

    This closes the Record Macro dialog box and begins recording your actions.

  4. Select any cell on your Excel spreadsheet, type your name into the selected cell, and then press Enter.
  5. Choose Developer ⇒   Code ⇒   Stop Recording (or click the Stop Recording button in the status bar).

Examining the macro

The macro was recorded in a new module named Module1. To view the code in this module, you must activate the Visual Basic Editor. You can activate the VB Editor in either of two ways:

  • Press Alt+F11.
  • Choose Developer ⇒   Code ⇒   Visual Basic.

In the VB Editor, the Project window displays a list of all open workbooks and add-ins. This list is displayed as a tree diagram, which you can expand or collapse. The code that you recorded previously is stored in Module1 in the current workbook. When you double-click Module1, the code in the module appears in the Code window.

The macro should look something like this:

Sub MyName()
'
' MyName Macro
'
' Keyboard Shortcut: Ctrl+Shift+N
'
ActiveCell.FormulaR1C1 = "Michael Alexander"

End Sub

The macro recorded is a Sub procedure named MyName. The statements tell Excel what to do when the macro is executed.

Notice that Excel inserted some comments at the top of the procedure. These comments are some of the information that appeared in the Record Macro dialog box. These comment lines (which begin with an apostrophe) aren’t really necessary, and deleting them has no effect on how the macro runs. If you ignore the comments, you'll see that this procedure has only one VBA statement:

ActiveCell.FormulaR1C1 = "Michael Alexander"

This single statement causes the name you typed while recording to be inserted into the active cell.

Testing the macro

Before you recorded this macro, you set an option that assigned the macro to the Ctrl+Shift+N shortcut key combination. To test the macro, return to Excel by using either of the following methods:

  • Press Alt+F11.
  • Click the View Microsoft Excel button on the VB Editor toolbar.

When Excel is active, activate a worksheet. (It can be in the workbook that contains the VBA module or in any other workbook.) Select a cell and press Ctrl+Shift+N. The macro immediately enters your name into the cell.

In the preceding example, notice that you selected the cell to be altered before you started recording your macro. This step is important. If you select a cell while the macro recorder is turned on, the actual cell that you selected is recorded into the macro. In such a case, the macro would always format that particular cell, and it would not be a general-purpose macro.

Editing the macro

After you record a macro, you can make changes to it (although you must know what you’re doing). For example, assume that you want your name to be bold. You could re-record the macro, but this modification is simple, so editing the code is more efficient. Press Alt+F11 to activate the VB Editor window. Then activate Module1 and insert the following statement before the End Sub statement:

ActiveCell.Font.Bold = True

The edited macro appears as follows:

Sub MyName()
'
' MyName Macro
'
' Keyboard Shortcut: Ctrl+Shift+N
'
ActiveCell.Font.Bold = True

ActiveCell.FormulaR1C1 = "Michael Alexander"

End Sub

Test this new macro, and you see that it performs as it should.

Comparing Absolute and Relative Macro Recording

Now that you’ve read about the basics of the Macro Recorder interface, it’s time to go deeper and begin recording macros. The first thing you need to understand before you begin is that Excel has two modes for recording — absolute reference and relative reference.

Recording macros with absolute references

Excel’s default recording mode is in absolute reference. As you may know, the term absolute reference is often used in the context of cell references found in formulas. When a cell reference in a formula is an absolute reference, it does not automatically adjust when the formula is pasted to a new location.

The best way to understand how this concept applies to macros is to try it out. Open the Chapter 1 Sample File.xlsx file and record a macro that counts the rows in the Branchlist worksheet. (See Figure 1-2.)

FIGURE 1-2: Your pre-totaled worksheet containing two tables.

The sample dataset used in this chapter can be found on this book’s companion website at www.dummies.com/go/excelmacros.

Follow these steps to record the macro:

  1. Before recording, make sure cell A1 is selected.
  2. Select Record Macro from the Developer tab.
  3. Name the macro AddTotal.
  4. Choose This Workbook for the save location.
  5. Click OK to start recording.

    At this point, Excel is recording your actions. While Excel is recording, perform the following steps:

    1. Select cell A16 and type Total in the cell.
    2. Select the first empty cell in Column D (D16) and enter = COUNTA(D2:D15).

      This gives a count of branch numbers at the bottom of column D. You need to use the COUNTA function because the branch numbers are stored as text.

    3. Click Stop Recording on the Developer tab to stop recording the macro.

The formatted worksheet should look something like the one in Figure 1-3.

FIGURE 1-3: Your post-totaled worksheet.

To see your macro in action, delete the total row you just added and play back your macro by following these steps:

  1. Select Macros from the Developer tab.
  2. Find and select the AddTotal macro you just recorded.
  3. Click the Run button.

If all goes well, the macro plays back your actions to a T and gives your table a total. Now here’s the thing: No matter how hard you try, you can’t make the AddTotal macro work on the second table (G1:I15 in Figure 1-3). Why? Because you recorded it as an absolute macro.

To understand what this means, examine the underlying code. To examine the code, select Macros from the Developer tab to get the Macro dialog box you see in Figure 1-4.

FIGURE 1-4: The Excel Macro dialog box.

Select the AddTotal macro and click the Edit button. This opens the Visual Basic Editor to show you the code that was written when you recorded your macro:

Sub AddTotal()

Range("A16").Select

ActiveCell.FormulaR1C1 = "Total"

Range("D16").Select

ActiveCell.FormulaR1C1 = "=COUNTA(R[-14]C:R[-1]C)"

End Sub

Pay particular attention to lines 2 and 4 of the macro. When you asked Excel to select cell range A16 and then D16, those cells are exactly what it selected. Because the macro was recorded in absolute reference mode, Excel interpreted your range selection as absolute. In other words, if you select cell A16, that cell is what Excel gives you. In the next section, you take a look at what the same macro looks like when recorded in relative reference mode.

Recording macros with relative references

In the context of Excel macros, relative means relative to the currently active cell. So you should use caution with your active cell choice — both when you record the relative reference macro and when you run it.

First, make sure the Chapter 1 Sample File.xlsx file is open. Then, use the following steps to record a relative-reference macro:

To download the Chapter 1 Sample file, visit www.dummies.com/go/excelmacros.

  1. Select the Use Relative References option from the Developer tab, as shown in Figure 1-5.
  2. Before recording, make sure cell A1 is selected.
  3. Select Record Macro from the Developer tab.
  4. Name the macro AddTotalRelative.
  5. Choose This Workbook for the save location.
  6. Click OK to start recording.
  7. Select cell A16 and type Total in the cell.
  8. Select the first empty cell in Column D (D16) and type = COUNTA(D2:D15).
  9. Click Stop Recording on the Developer tab to stop recording the macro.

FIGURE 1-5: Recording a macro with relative references.

At this point, you have recorded two macros. Take a moment to examine the code for your newly created macro.

Select Macros from the Developer tab to open the Macro dialog box. Here, choose the AddTotalRelative macro and click Edit.

Again, this opens the Visual Basic Editor to show you the code that was written when you recorded your macro. This time, your code looks something like the following:

Sub AddTotalRelative()

ActiveCell.Offset(15, 0).Range("A1").Select

ActiveCell.FormulaR1C1 = "Total"

ActiveCell.Offset(0, 3).Range("A1").Select

ActiveCell.FormulaR1C1 = "=COUNTA(R[-14]C:R[-1]C)"

End Sub

Notice that there are no references to any specific cell ranges at all (other than the starting point “A1”). Let’s take a quick look at what the relevant parts of this VBA code really mean.

Notice that in line 2, Excel uses the Offset property of the active cell. This property tells the cursor to move a certain number of cells up or down and a certain number of cells left or right.

The Offset property code tells Excel to move 15 rows down and 0 columns across from the active cell (in this case, A1). There’s no need for Excel to explicitly select a cell as it did when recording an absolute reference macro.

To see this macro in action, delete the total row for both tables and do the following:

  1. Select cell A1.
  2. Select Macros from the Developer tab.
  3. Find and select the AddTotalRelative macro.
  4. Click the Run button.
  5. Now select cell F1.
  6. Select Macros from the Developer tab.
  7. Find and select the AddTotalRelative macro.
  8. Click the Run button.

Notice that this macro, unlike your previous macro, works on both sets of data. Because the macro applies the totals relative to the currently active cell, the totals are applied correctly.

For this macro to work, you simply need to ensure that

  • You’ve selected the correct starting cell before running the macro.
  • The block of data has the same number of rows and columns as the data on which you recorded the macro.

Hopefully, this simple example has given you a firm grasp of macro recording with both absolute and relative references.