Chapter 12: Macros
Learning Objectives
- Show the Developer tab, enable macros in a workbook, and save a macro-enabled workbook.
- Record and name simple macros, with absolute or relative references.
- Run macros, change their shortcut keys, and make simple edits in the Visual Basic Editor.
- Copy macros from one workbook to another.
A macro is a recorded set of steps that Excel can repeat with one click or keystroke. If you format a weekly report the same way every Monday, you can record yourself doing it once and play it back from then on. Behind the scenes, Excel writes each step in VBA (Visual Basic for Applications), a programming language. MO-211 doesn't expect you to program. It expects you to record, name, run and make simple edits to macros, to copy them between workbooks, and to manage the security settings that control them.
12.1 Macro security and file formats
12.1.1 The Developer tab
Macro commands are on the Developer tab, which is hidden at first. To show it, choose File › Options › Customize Ribbon, check Developer in the list on the right, and click OK.
The View › Macros button also has Record Macro, View Macros and Use Relative References, so you can record without the Developer tab. A Record Macro button also appears at the left end of the status bar.
12.1.2 Enabling macros in a workbook
Macros can do almost anything Excel can do, including harmful things, so Excel blocks them by default in files you didn't create. When you open a workbook with macros, a yellow Security Warning bar says Macros have been disabled:
- Click Enable Content to enable the macros and mark the file as trusted, so you won't be asked again.
- Or choose File › Info › Enable Content › Advanced Options and select Enable content for this session to enable them only until you close the file.
A file downloaded from the internet or received by email may show a red Security Risk bar instead, with no Enable button. To allow its macros, close it, right-click the file in File Explorer, choose Properties, check Unblock and click OK, then reopen it.
12.1.3 Macro settings
File › Options › Trust Center › Trust Center Settings › Macro Settings sets what Excel does with macros in files that aren't trusted:
| Setting | Effect |
|---|---|
| Disable VBA macros without notification | Blocks all macros silently. |
| Disable VBA macros with notification | Blocks macros but shows the Security Warning bar. This is the default. |
| Disable VBA macros except digitally signed macros | Runs only macros signed by a trusted publisher. |
| Enable VBA macros | Runs every macro without asking. Not recommended. |
Trusted Locations in the Trust Center lists folders whose files always open with macros enabled. Files in trusted locations skip the warning.
"Enable the macros in the workbook" on the exam usually means clicking Enable Content on the Security Warning bar. "Configure Excel so that all macros are disabled but users are notified" means the Trust Center setting Disable VBA macros with notification.
12.1.4 Macro-enabled file formats
A regular workbook (.xlsx) can't store macros. If you save a workbook with macros as .xlsx, Excel warns that the macros will be lost. Use one of these formats instead:
| Format | Extension |
|---|---|
| Excel Macro-Enabled Workbook | .xlsm |
| Excel Binary Workbook | .xlsb |
| Excel Macro-Enabled Template | .xltm |
Choose the format from Save as type in File › Save As.
12.2 Recording and naming macros
12.2.1 Planning the recording
The recorder captures every step you take, including mistakes and unnecessary clicks. Before you record:
- Know the steps. Practice them once, or write them down.
- Decide where to start. If the macro should always format A1:F1, it doesn't matter which cell is active when you start. If it should format "the row the user is on," you'll need relative references (see below).
- Decide where to store the macro.
12.2.2 Recording
- Choose Developer › Record Macro (or View › Macros › Record Macro).
- Fill in the Record Macro dialog box:
- Macro name: the name of the macro (see the rules below).
- Shortcut key: optional. Type a letter to run the macro with Ctrl+that letter. Type a capital letter (hold Shift) to use Ctrl+Shift+the letter. A shortcut overrides Excel's own shortcut while the workbook is open, so Ctrl+Shift combinations are safer.
- Store macro in: This Workbook keeps the macro in the current file. New Workbook puts it in a new file. Personal Macro Workbook saves it in a hidden workbook, PERSONAL.XLSB, that opens whenever Excel does, so the macro is available in every workbook.
- Description: optional notes about what the macro does.
- Click OK. The recorder is now running.
- Do the steps.
- Choose Developer › Stop Recording (or click the square Stop button on the status bar).
12.2.3 Naming rules
Macro names follow rules much like range names:
- They must start with a letter.
- They can contain letters, numbers and underscores, but no spaces or other punctuation.
- They can't look like a cell reference (such as
AB12) or use a word VBA reserves.
FormatReport, Format_Report and AddTotals2 are fine. Format Report and 2Totals are not.
12.2.4 Absolute and relative references
By default the recorder uses absolute references. If you click C5 while recording, the macro always selects C5, no matter which cell was active when you ran it.
With Use Relative References turned on (Developer › Use Relative References, which stays highlighted while it's on), the recorder records movement relative to the starting cell. If you start in A1 and click C5, the macro moves two columns right and four rows down from wherever you run it.
Use relative references for macros that should work on whichever cell or row is selected, such as "format the current row as a total." Turn the setting on before you make the steps that should be relative. You can switch it on and off during a recording.
Tasks spell out the recording settings: "Record a macro named Highlight_Row that is stored in this workbook and runs when the user presses Ctrl+Shift+H. The macro should apply the yellow fill color to the row that contains the active cell." The details to get right: the name with its underscore, This Workbook, capital H in the shortcut box, and relative references so it works on any row.
12.3 Running and editing macros
12.3.1 Running a macro
There are several ways to run a macro:
- Press its shortcut key.
- Choose Developer › Macros (or View › Macros, or Alt+F8), select the macro and click Run.
- Click a button or shape it's assigned to. Insert a shape (Insert › Shapes), right-click it, choose Assign Macro and pick the macro. You can also use a button from Developer › Insert › Button (Form Control).
- Click a Quick Access Toolbar button. Add one from File › Options › Quick Access Toolbar, choosing Macros in the Choose commands from list.
You can't undo a macro with Ctrl+Z. Save the workbook before you test a macro, so you can go back if it does something unexpected.
12.3.2 The Macro dialog box
Developer › Macros (Alt+F8) lists the macros in open workbooks. Besides Run:
- Step Into opens the macro in the Visual Basic Editor and runs it one line at a time.
- Edit opens the macro's code in the Visual Basic Editor.
- Delete removes the macro.
- Options changes the macro's shortcut key and description.
The Macros in list chooses whether to show macros from all open workbooks or just one.
12.3.3 The Visual Basic Editor
Click Edit in the Macro dialog box, or press Alt+F11, to open the Visual Basic Editor (VBE). The Project Explorer on the left lists each open workbook as a VBAProject. Recorded macros are stored in Modules, usually Module1. Double-click a module to see its code.
A recorded macro looks something like this:
Sub FormatHeader()
'
' FormatHeader Macro
' Bold, center and fill the heading row.
'
' Keyboard Shortcut: Ctrl+Shift+H
'
Range("A1:F1").Select
Selection.Font.Bold = True
Selection.HorizontalAlignment = xlCenter
With Selection.Interior
.Color = 15773696
End With
End SubHow to read it:
Sub FormatHeader()starts the macro, andEnd Subends it. The word afterSubis the macro's name.- Lines starting with an apostrophe (
') are comments. They're notes for people and are ignored when the macro runs. The recorder adds the description and shortcut as comments. - Each other line is one step.
Range("A1:F1").Selectselects A1:F1, and the next lines format the selection.
12.3.4 Making simple edits
MO-211 asks for simple edits, such as:
| To | Change |
|---|---|
| Change the range the macro works on | Range("A1:F1") to Range("A1:H1") |
| Change a value | .Color = 15773696 to another number, or Selection.Font.Size = 12 to 14 |
| Remove a step | Delete the whole line |
| Rename the macro | The name after Sub, such as Sub FormatHeader() to Sub Format_Header(). Keep the parentheses. |
| Add a comment | A new line starting with ' |
After editing, close the editor (or press Alt+Q) to return to Excel. You don't have to save separately in the editor. Saving the workbook (as .xlsm) saves the code.
Changing the name after Sub renames the macro, but the shortcut key stays assigned. Recorded text in the comments, such as the old name, doesn't update. That's fine, because comments don't affect anything. Make sure the new name still follows the naming rules.
12.4 Copying macros between workbooks
A macro stored in one workbook works only while that workbook is open. To make it part of another workbook, copy its module.
12.4.1 Dragging a module
- Open both workbooks.
- Press Alt+F11 to open the Visual Basic Editor. If the Project Explorer isn't showing, choose View › Project Explorer (Ctrl+R).
- Expand the source workbook's project and its Modules folder.
- Drag the module (such as Module1) onto the destination workbook's project.
A copy of the module, with all its macros, appears in the destination workbook. Save the destination as a macro-enabled workbook.
12.4.2 Copying the code
You can also copy just one macro:
- In the source module, select everything from
SubthroughEnd Suband copy it (Ctrl+C). - In the destination project, choose Insert › Module, or open an existing module.
- Paste (Ctrl+V).
12.4.3 Exporting and importing
To move a module through a file, right-click it in the Project Explorer and choose Export File, which saves a .bas file. In the other workbook's project, right-click and choose Import File.
To make a macro available in every workbook, store it in the Personal Macro Workbook. Drag its module into the VBAProject (PERSONAL.XLSB) project. If PERSONAL.XLSB doesn't exist yet, record any short macro with Store macro in: Personal Macro Workbook to create it.
12.5 Practice
Simmy assessment goes here. Exam-style tasks on enabling macros, recording and naming macros, relative references, editing a macro, and copying macros between workbooks. When a student misses a task, Simmy builds the AI prompt (the task as worded, what the student did, and the correct result).
Starting data. Two workbooks.
Weekly Report.xlsm (opens with the Security Warning bar), sheet Report (A1:F30): row 1 headings Week, Store, Sales, Returns, Net, Notes; 29 rows of data. It contains Module1 with this macro:
Sub AddTitle()
' Inserts a title row above the data.
Rows("1:1").Select
Selection.Insert Shift:=xlDown
Range("A1").Select
ActiveCell.FormulaR1C1 = "Weekly Sales Report"
Selection.Font.Size = 14
Selection.Font.Bold = True
End SubStore Summary.xlsx: one sheet, Summary, with a similar layout and no macros.
Tasks.
- Enable the macros in the Weekly Report workbook. Expected result: content enabled (macros allowed to run). Objective: Enable macros in a workbook.
- Record a macro named Format_Headings that is stored in this workbook and runs when the user presses Ctrl+Shift+F. The macro should make the text in A1:F1 bold, center it, and apply the Accent1 cell style. Expected result: macro Format_Headings in Weekly Report's module, shortcut Ctrl+Shift+F, selecting A1:F1 and applying bold, centering and the Accent1 style. Objective: Record simple macros; Name simple macros.
- Record a macro named Shade_Row that is stored in this workbook and applies a light gray fill to the cells in columns A through F of whichever row contains the active cell. Expected result: Shade_Row recorded with relative references so it works on any row. Objective: Record simple macros.
- Edit the AddTitle macro so that the title text is Weekly Store Report and the font size is 16. Expected result: code reads
ActiveCell.FormulaR1C1 = "Weekly Store Report"andSelection.Font.Size = 16. Objective: Edit simple macros. - Rename the AddTitle macro to Add_Title. Expected result:
Sub Add_Title(); no macro named AddTitle remains. Objective: Name simple macros. - Copy all macros in the Weekly Report workbook to the Store Summary workbook. Save Store Summary in a format that keeps the macros. Expected result: Store Summary contains the Add_Title, Format_Headings and Shade_Row macros (the recorder may have put the new macros in a second module, so every module must be copied); saved as Store Summary.xlsm. Objective: Copy macros between workbooks.