Chapter 1
In This Chapter
Understanding why you should use macros
Recording macros
Understanding macro security
Seeing 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. On your phone, you first manually dial and save the number. Later, you can redial those numbers with the touch of a button. In Excel, you start recording a macro, and then you perform your intended actions. While you record, Excel gets busy in the background, translating your keystrokes and mouse clicks to a macro. This written code is known as Visual Basic for Applications (VBA). After the macro is recorded, you can play back those actions anytime you want.
In this chapter, you explore macros and learn how you can use them to automate recurring processes to simplify your life.
The first step in using macros is admitting you have a problem. Actually, you may have several problems:
To start recording your first macro, you need to find 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:
Now that the Developer tab appears in the Excel ribbon, you can start Macro Recorder. Select Record Macro from the Developer tab. The Record Macro dialog box appears, as shown in Figure 1-1.
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 in a worksheet cell:
In the User Name field, enter a new single-word name for the macro to replace the default Macro1 name.
A good name for this example is MyName.
In the Shortcut Key field, enter an uppercase N.
You've just assigned this macro to the shortcut key Ctrl+Shift+N.
The macro was recorded in a new module named Module1. To view the code in this module, you must activate Visual Basic (VB) Editor. You can activate VB Editor in either of two ways:
In 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 recorded macro is a Sub procedure named MyName. The statements tell Excel what to do when the macro is executed.
At the top of the procedure, note that Excel inserted some comments, which consist of information from the Record Macro dialog box. These comment lines (which begin with an apostrophe) aren’t 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 inserts in the active cell the name you typed while recording.
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:
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.
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 editing the code is more efficient because this modification is simple. Press Alt+F11 to activate the VB Editor window. Then double-click 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.
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.
Excel’s default recording mode is absolute reference. 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.)
Follow these steps to record the macro:
Click OK to start recording.
At this point, Excel is recording your actions.
Select the first empty cell in Column D (D16) and type = COUNTA(D2:D15).
This formula gives a count of branch numbers at the bottom of column D. You use the COUNTA function because the branch numbers are stored as text.
Click Stop Recording on the Developer tab to stop recording the macro.
The formatted worksheet should look like something like the one in Figure 1-3.
To see your macro in action, delete the Total row you just added and play back your macro by following these steps:
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. Why? Because you recorded it as an absolute macro.
To understand what this means, examine the underlying code by selecting Macros on the Developer tab. The Macro dialog box appears, as shown in Figure 1-4.
Select the AddTotal macro and click the Edit button. Visual Basic Editor opens and displays 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 the two lines of code that select range A16 and range D16. Because the macro was recorded in absolute reference mode, Excel interpreted your range selection as absolute cell references. In other words, no matter where your cursor is in your workbook, when you run the recorded macro, Excel will select cell A16 and then cell D16. In the next section, you take a look at what the same macro looks like when recorded in relative reference mode.
A relative reference means relative to the currently active cell. So 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. (This file is available on this book’s companion website at
www.dummies.com/extras/excelmacros
.) Then, use the following steps to record a relative reference macro:
At this point, you've recorded two macros. Take a moment to examine the code for your newly created macro by selecting Macros on the Developer tab to open the Macro dialog box. Choose the AddTotalRelative macro and click Edit.
Again, Visual Basic Editor opens and shows 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
First note that the code does not contain references to specific cell ranges (other than the starting point, A1). Note that in this macro, 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.
In this case, the Offset property code tells Excel to move 15 rows down and 0 columns across from the active cell (A1). Because the macro was recorded using relative reference, Excel will not explicitly select a particular 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:
Note 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
I hope this simple example has given you a firm grasp of macro recording with both absolute and relative references.
At this point, you should feel comfortable recording your own Excel macros. In this section, I describe some other important concepts you’ll need to keep in mind when working with macros.
Beginning with Excel 2007, Excel workbooks were given the standard file extension .xlsx. Files with the .xlsx extension cannot contain macros. If your workbook contains macros and you then save that workbook as an .xlsx file, your macros are removed automatically. Excel warns you that macro content will be disabled when saving a workbook with macros as an .xlsx file.
If you want to retain the macros, you must save your file as an Excel macro-enabled workbook. This gives your file an .xlsm extension. The idea is that all workbooks with an .xlsx file extension are automatically known to be safe, whereas you can recognize .xlsm files as a potential threat.
With the release of Office 2010, Microsoft introduced significant changes to its Office security model. One of the most significant changes is the concept of trusted documents. Without getting into the technical minutia, a trusted document is essentially a workbook you have deemed to be safe.
If you open a workbook that contains macros in Excel 2010 or later, you see a yellow bar message under the ribbon stating that macros (active content) have been disabled.
If you click Enable, the workbook automatically becomes a trusted document. This means you no longer are prompted to enable the content as long as you open that file on your computer. The basic idea is that if you tell Excel that you trust a particular workbook by enabling macros, it is highly likely that you will enable macros each time you open the workbook. Thus, Excel remembers that you’ve enabled macros before and inhibits any further messages about macros for that workbook.
This feature is great news for you and your clients. After enabling your macros one time, they won’t be annoyed at the constant messages about macros, and you won't have to worry that your macro-enabled dashboard will fall flat because macros have been disabled.
If the thought of any macro message coming up (even one time) unnerves you, set up a trusted location for your files. A trusted location is a directory that is deemed a safe zone where only trusted workbooks are placed. A trusted location allows you and your clients to run a macro-enabled workbook with no security restrictions as long as the workbook is in that location.
To set up a trusted location, follow these steps:
On the Developer tab, select the Macro Security button.
This activates the Trust Center dialog box.
On the left, click Trusted Locations.
The Trusted Locations menu appears (see Figure 1-6), displaying all the directories that are considered trusted.
After you specify a trusted location, any Excel file that is opened from this location will have macros automatically enabled.
Most user-created macros are designed for use in a specific workbook, but you may want to use some macros in all your work. You can store these general-purpose macros in the personal macro workbook so that they’re always available to you. The personal macro workbook is loaded whenever you start Excel. This file, named personal.xlsb, doesn't exist until you record a macro using the personal macro workbook as the destination.
To record the macro in your personal macro workbook, select the Personal Macro Workbook option in the Record Macro dialog box before you start recording. This option is in the Store Macro In drop-down list (refer to Figure 1-1).
If you store macros in the personal macro workbook, you don’t have to remember to open the personal macro workbook when you load a workbook that uses macros. When you want to exit, Excel asks whether you want to save changes to the personal macro workbook.
When you create macros, you may want to have a clear and easy way to run each one. A basic button can provide a simple but effective user interface.
As luck would have it, Excel offers a set of form controls for creating user interfaces directly on spreadsheets. Several types of form controls are available, from buttons (the most commonly used control) to scrollbars.
The idea behind using a form control is simple. You place a form control on a spreadsheet and then assign a macro to it — that is, a macro you’ve already recorded. When the control is clicked, the macro is executed, or played.
Take a moment to create a button for the AddTotalRelative macro you created earlier. Here’s how:
Click the location where you want to place your button.
When you drop the button control on your spreadsheet, the Assign Macro dialog box appears, as shown in Figure 1-8.
At this point, you have a button that runs your macro when you click it! Keep in mind that all controls in the Form Controls group (refer to Figure 1-7) work in the same way as the button form control used in this example. That is to say, you assign a macro to run when the control is selected.
You can assign a macro not only to a form control on a spreadsheet but also to a button in Excel’s Quick Access toolbar. The Quick Access toolbar sits either above or below the ribbon. You can add a custom button that will run your macro by following these steps:
Right-click your Quick Access toolbar and select Customize Quick Access Toolbar.
The dialog box illustrated in Figure 1-9 appears.
Covering the fundamentals of building and using macros is one thing. Coming up with good ways to incorporate them in your reporting processes is another. In this section, you take a moment to review a few examples of how macros automate simple reporting tasks.
The most common use of macros is in navigation. Workbooks that have many worksheets or tabs can be frustrating to navigate. To help your audience, you can create a switchboard, like the one shown in Figure 1-10. When users click the Example 1 button, for example, they're taken to the Example 1 sheet.
Creating a macro to navigate to a sheet is quite simple:
In the example illustrated in Figure 1-11, macros allow a user to change the perspective of the chart simply by selecting one of the buttons shown.
Figure 1-12 reveals that the chart is actually a pivot chart tied to a pivot table. The recorded macros assigned to the buttons do nothing more than rearrange the pivot table to slice the data using various pivot fields.
Here are the high-level steps needed to create this type of setup:
You can fire your new macros in turn to see your pivot field dynamically move back and forth.
The last two examples demonstrate that you can record any action that you find of value. That is, if you think users would appreciate a certain feature being automated for them, why not record a macro to do so?
In Figure 1-13, note that users can filter the pivot table for the top or bottom 20 customers. Because the steps for this filter have been recorded, users save time and effort and can benefit from this functionality without having to know the steps involved. Also, recording a specific action enables you to manage risk because your users will interact with your reports in a method that you've developed and tested.
Figure 1-14 demonstrates how you can give your audience a quick and easy way to see the same data on different charts. Don’t laugh too quickly at the apparent uselessness of this example. It’s not uncommon to be asked to see the same data different ways.
Instead of taking up real estate with multiple charts, just record a macro that changes the chart type. Your clients will be able to switch views to their heart’s content.
18.222.161.187