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.

Beginner 15 min read

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.

ABCD
1DateRegionSalespersonAmount
22026-03-02NorthMaria Lopez1250
32026-03-02SouthTom Becker980.5
42026-03-03NorthAiko Tanaka2310
52026-03-04WestMaria Lopez640

The raw weekly export (before)

Type this data into a new sheet, click any cell, and then:

  1. 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).
  2. 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.
  3. 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.
  4. In Store macro in, keep This Workbook for now.
  5. 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.

  1. Click cell A1, then select A1:D1.
  2. Press Ctrl+B (Cmd+B) for bold and pick a light blue fill from Home > Fill Color.
  3. Select D2:D5 and apply the Currency format from the Number Format box on the Home tab.
  4. Select columns A:D and double-click the border between two column letters to AutoFit them.
  5. Click A1.
  6. Click Developer > Stop Recording (or the square stop icon in the status bar).
ABCD
1DateRegionSalespersonAmount
22026-03-02NorthMaria Lopez$1,250.00
32026-03-02SouthTom Becker$980.50
42026-03-03NorthAiko Tanaka$2,310.00
52026-03-04WestMaria 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):

VBA
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 Sub
Typical recorder output for the formatting job

Let us read it line by line:

  • The lines starting with ' are comments the recorder wrote from your description and shortcut.
  • Range("A1").Select and Range("A1:D1").Select are your clicks. The first is useless, because you immediately selected something else.
  • Selection.Font.Bold = True means "make whatever is selected bold". Selection is the range that was selected at that moment.
  • The With Selection.Interior ... End With block sets the fill. With lets several lines share the same object, so .Pattern means Selection.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.AutoFit fits 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 If or 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:

VBA
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 Sub
The same job, cleaned up

What changed:

  • No Select and no Selection at all. Each action goes straight to the range.
  • Interior.Color = RGB(221, 235, 247) sets a light blue in one line. RGB takes red, green and blue values from 0 to 255.
  • lastRow holds 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 Long declares the variable, which Option Explicit requires (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:

VBA
Sub MarkChecked()
    ActiveCell.Offset(0, 1).Range("A1").Select
    ActiveCell.FormulaR1C1 = "Checked"
    ActiveCell.Offset(0, 1).Range("A1").Select
    ActiveCell.FormulaR1C1 = "=TODAY()"
End Sub
Recorded with Use Relative References switched on

ActiveCell.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:

VBA
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 Sub
Cleaned relative macro

Where recorded macros are stored

The Store macro in list in the Record Macro dialog has three choices:

ChoiceWhere the code goesUse it when
This WorkbookA module in the current fileThe macro belongs to this file only
New WorkbookA module in a brand-new workbookRarely useful
Personal Macro WorkbookPERSONAL.XLSB, opened invisibly with ExcelYou 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").Select if 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?

2. How do you clean up a pair of lines like Range("A1:D1").Select and Selection.Font.Bold = True?

3. What does "Use Relative References" change?

4. Where should you store a macro that you want to use in every workbook on your computer?

5. Which of these can the macro recorder write for you?