VBA course · Lesson 3 of 33
The macro recorder: record, read and clean up code
Record a macro, run it again, read the code Excel wrote, switch to relative references and clean recorded code into short, reliable VBA.
The macro recorder watches what you do in Excel and writes the matching VBA code for you. It is the quickest way to automate a simple, repetitive job, and it is an excellent teacher: whenever you wonder "what is the VBA for this?", you can record yourself doing it and read the result. In this lesson you record a real formatting job, play it back, look at the code it produced, and then clean that code up so it is shorter and more dependable.
Recording your first macro
Imagine that every Monday you receive a sales export that looks like the grid below. Every week you make the header bold with a fill colour, format the amounts as currency, and widen the columns. That is the perfect job for the recorder.
| A | B | C | D | |
|---|---|---|---|---|
| 1 | Date | Region | Salesperson | Amount |
| 2 | 2026-03-02 | North | Maria Lopez | 1250 |
| 3 | 2026-03-02 | South | Tom Becker | 980.5 |
| 4 | 2026-03-03 | North | Aiko Tanaka | 2310 |
| 5 | 2026-03-04 | West | Maria Lopez | 640 |
The raw weekly export (before)
Type this data into a new sheet, click any cell, and then:
- Click Developer > Record Macro (or the small record icon in the status bar at the bottom left; on a Mac Tools > Macro > Record New Macro also works).
- In the dialog, give the macro a name:
FormatSalesExport. Names must start with a letter and cannot contain spaces; use capital letters or underscores to separate words. - Optionally assign a shortcut key. Avoid common ones: Ctrl+C would replace Copy while the workbook is open. Holding Shift gives safer combinations such as Ctrl+Shift+F.
- In Store macro in, keep This Workbook for now.
- Type a short description, such as "Formats the weekly sales export", and click OK.
From this moment, everything you do is recorded. Work calmly; the recorder does not record time, only actions.
- Click cell A1, then select A1:D1.
- Press Ctrl+B (Cmd+B) for bold and pick a light blue fill from Home > Fill Color.
- Select D2:D5 and apply the Currency format from the Number Format box on the Home tab.
- Select columns A:D and double-click the border between two column letters to AutoFit them.
- Click A1.
- Click Developer > Stop Recording (or the square stop icon in the status bar).
| A | B | C | D | |
|---|---|---|---|---|
| 1 | Date | Region | Salesperson | Amount |
| 2 | 2026-03-02 | North | Maria Lopez | $1,250.00 |
| 3 | 2026-03-02 | South | Tom Becker | $980.50 |
| 4 | 2026-03-03 | North | Aiko Tanaka | $2,310.00 |
| 5 | 2026-03-04 | West | Maria Lopez | $640.00 |
After the recorded steps: bold blue header, currency amounts, fitted columns
Running the recorded macro
Paste the raw data onto a new sheet, then press Alt+F8 (Mac: Opt+F8), pick FormatSalesExport and click Run. The formatting appears in an instant. You can also use the shortcut you assigned. Remember to save the workbook as .xlsm, as explained in What is VBA? Macros, when to use them and macro security.
Reading the recorded code
Press Alt+F11 to open the editor (The Developer tab and the VBA editor). The recorder created a new module, usually Module1, under Modules. Double-click it. You will see something like this (the exact lines depend on your Excel version and on what you clicked):
Sub FormatSalesExport()
'
' FormatSalesExport Macro
' Formats the weekly sales export
'
' Keyboard Shortcut: Ctrl+Shift+F
'
Range("A1").Select
Range("A1:D1").Select
Selection.Font.Bold = True
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent1
.TintAndShade = 0.799981688894314
.PatternTintAndShade = 0
End With
Range("D2:D5").Select
Selection.NumberFormat = "$#,##0.00"
Columns("A:D").Select
Columns("A:D").EntireColumn.AutoFit
Range("A1").Select
End SubLet us read it line by line:
- The lines starting with
'are comments the recorder wrote from your description and shortcut. Range("A1").SelectandRange("A1:D1").Selectare your clicks. The first is useless, because you immediately selected something else.Selection.Font.Bold = Truemeans "make whatever is selected bold".Selectionis the range that was selected at that moment.- The
With Selection.Interior ... End Withblock sets the fill.Withlets several lines share the same object, so.PatternmeansSelection.Interior.Pattern. The recorder writes every property it can see, even the ones you did not change. Selection.NumberFormat = "$#,##0.00"is the currency format.Columns("A:D").EntireColumn.AutoFitfits the column widths.
Notice the pattern: select something, then do something to the selection. That is how a person works, but it is not how good code works.
Why recorded code needs cleaning
Recorded code works, but it has typical weaknesses:
- It selects everything. Selecting cells is slow, makes the screen flicker, and fails if the sheet is not active.
- It is full of fixed addresses.
Range("D2:D5")only covers four rows. Next week's export has 412 rows, and the macro will format only the first four. - It records too much. Five lines for a fill colour where one would do, scroll movements, extra clicks.
- It cannot make decisions or repeat. The recorder never writes
Ifor loops. You add those yourself (Making decisions: If, ElseIf and Select Case, For loops: For...Next and For Each).
Cleaning up the code
The golden rule is: wherever you see X.Select followed by Selection.Y, replace both lines with X.Y. Then remove anything you did not mean to set, and replace fixed sizes with ranges that adapt to the data. Here is the cleaned version:
Option Explicit
Sub FormatSalesExport()
' Formats the weekly sales export on the active sheet.
' Works for any number of rows.
Dim lastRow As Long
' Find the last used row in column A
lastRow = Cells(Rows.Count, "A").End(xlUp).Row
' Header: bold with a light blue fill
With Range("A1:D1")
.Font.Bold = True
.Interior.Color = RGB(221, 235, 247)
End With
' Amounts as currency, from row 2 down to the last row
Range("D2:D" & lastRow).NumberFormat = "$#,##0.00"
' Fit the column widths
Columns("A:D").AutoFit
End SubWhat changed:
- No
Selectand noSelectionat all. Each action goes straight to the range. Interior.Color = RGB(221, 235, 247)sets a light blue in one line.RGBtakes red, green and blue values from 0 to 255.lastRowholds the number of the last filled row, so the currency format covers exactly the data, whether it is 4 rows or 4,000. You will learn this technique properly in Find the last row and build dynamic ranges in VBA; for now just reuse the line.Dim lastRow As Longdeclares the variable, whichOption Explicitrequires (Variables and data types: Dim, Option Explicit and scope).
The cleaned macro is shorter, faster, and does the right thing on next week's file. This "record, then tidy" approach is how many professionals still write code for unfamiliar parts of Excel.
Absolute and relative recording
By default the recorder notes exact addresses: you clicked D2, so the code says Range("D2"). Sometimes you want the macro to work wherever the active cell is. For that, click Developer > Use Relative References before you start recording (the button stays highlighted while it is on).
Suppose you want a macro that writes "Checked" and today's date in the two cells to the right of whatever cell you are on. Record it with relative references on, and you get code like this:
Sub MarkChecked()
ActiveCell.Offset(0, 1).Range("A1").Select
ActiveCell.FormulaR1C1 = "Checked"
ActiveCell.Offset(0, 1).Range("A1").Select
ActiveCell.FormulaR1C1 = "=TODAY()"
End SubActiveCell.Offset(0, 1) means "zero rows down, one column to the right of the active cell". The odd .Range("A1") that follows is a recorder quirk meaning "the first cell of that range"; you can drop it. Cleaned up, and storing a fixed date rather than a TODAY formula that would change tomorrow:
Option Explicit
Sub MarkChecked()
' Writes "Checked" and today's date to the right of the active cell
ActiveCell.Offset(0, 1).Value = "Checked"
ActiveCell.Offset(0, 2).Value = Date
End SubWhere recorded macros are stored
The Store macro in list in the Record Macro dialog has three choices:
| Choice | Where the code goes | Use it when |
|---|---|---|
| This Workbook | A module in the current file | The macro belongs to this file only |
| New Workbook | A module in a brand-new workbook | Rarely useful |
| Personal Macro Workbook | PERSONAL.XLSB, opened invisibly with Excel | You want the macro in every workbook on your PC |
The Personal Macro Workbook is a hidden workbook that Excel creates the first time you record into it and then opens silently every time Excel starts. It is great for personal helpers such as "paste values" or "format as report". When you close Excel after recording into it, Excel asks whether to save changes to the Personal Macro Workbook; answer Save, or the macro is lost. On Windows the file lives in the XLSTART folder of your user profile. On a Mac it is called Personal Macro Workbook and is kept in Excel's startup folder inside your Library. To edit it, open the editor and look for VBAProject (PERSONAL.XLSB). VBA best practices: clean code, sharing and security has more on organising it.
What the recorder cannot record
The recorder is useful but limited. It records results of actions, not your intentions. It cannot record:
- decisions ("if the amount is negative, colour it red"),
- repetition ("do this for every sheet"),
- messages and questions to the user,
- anything you do in the VBA editor itself,
- some newer features, such as certain chart formatting and some Power Query steps, which are either skipped or recorded only partly.
It also records mistakes. If you click the wrong cell and then correct it, both clicks end up in the code. That is fine; you remove them while tidying.
Common mistakes
- Recording on the wrong sheet. The recorder writes
Sheets("Sheet2").Selectif you switch sheets, and the macro will fail later in a workbook without a Sheet2. Start recording on the sheet you want, or remove such lines. - Forgetting to stop recording. Everything you do afterwards ends up in the macro. Look at the status bar: a square stop icon means you are still recording.
- Saving as .xlsx. The recorded module is thrown away. Use .xlsm.
- Overwriting a built-in shortcut. Ctrl+Z or Ctrl+S as a macro shortcut takes over Undo or Save in that workbook.
- Expecting Undo to work. Running a macro clears the undo history, so practise on copies.
Check yourself
1. What is the main weakness of the line Range("D2:D5").NumberFormat = "$#,##0.00" in a recorded macro?
The recorder writes the exact cells you touched. Replace fixed addresses with a range that is built from the last row.
2. How do you clean up a pair of lines like Range("A1:D1").Select and Selection.Font.Bold = True?
Acting directly on a range is faster and does not depend on what is selected.
3. What does "Use Relative References" change?
With relative references on, the code says "one column right of the active cell" instead of a fixed address.
4. Where should you store a macro that you want to use in every workbook on your computer?
PERSONAL.XLSB opens hidden every time Excel starts, so its macros are always available.
5. Which of these can the macro recorder write for you?
The recorder only writes the actions you perform. Decisions and loops must be added by hand.