Tabellab

Recording a Macro

Lesson 1 of 8Reading

Excel writes the code for you

The Macro Recorder watches what you do and writes the equivalent VBA into a module. You need to know no syntax at all to use it, which makes it the fastest way to find out how something is expressed in code. What it gives you is a first draft, not a macro — this lesson does the whole round trip: something to practise on, the recording, and the same job written properly.

First, something to record against

Press Alt+F11, choose Insert → Module, paste this in and press F5. It builds a small untidy export on a new sheet, so nothing of yours is at risk and you can start over as often as you like.

Option Explicit

Sub MakeDemoExport()
    Dim ws As Worksheet
    Dim i As Long

    Set ws = ThisWorkbook.Worksheets.Add
    ws.Name = "Export " & Format(Now, "hh-mm-ss")

    ws.Range("A1:D1").Value = Array("date", "customer", "units", "amount")

    For i = 1 To 20
        ws.Cells(i + 1, 1).Value = DateSerial(2026, 2, i)
        ws.Cells(i + 1, 2).Value = "Customer " & Chr(64 + i)
        ws.Cells(i + 1, 3).Value = 5 + (i Mod 7)
        ws.Cells(i + 1, 4).Value = 149.5 * i
    Next i
End Sub

Now record the clean-up

  • Start — Developer → Record Macro, or the small record button on the status bar. If the Developer tab is missing: File → Options → Customize Ribbon.
  • Name it Macro1 for now and leave Store macro in on This Workbook.
  • Do the job — bold row 1 and colour it, format column A as a date and column D with two decimals, sort by amount descending, autofit A:D.
  • Stop — Developer → Stop Recording, then Alt+F11 and read what Excel wrote. Recording without reading teaches you nothing.
Sub Macro1()
'
' Macro1 Macro
'

'
    Rows("1:1").Select
    Selection.Font.Bold = True
    With Selection.Interior
        .Pattern = xlSolid
        .PatternColorIndex = xlAutomatic
        .ThemeColor = xlThemeColorLight2
        .TintAndShade = 0.799981688894314
        .PatternTintAndShade = 0
    End With
    Range("A2:A21").Select
    Selection.NumberFormat = "dd mmm yyyy"
    Range("D2:D21").Select
    Selection.NumberFormat = "#,##0.00"
    Range("A1:D21").Select
    ActiveWorkbook.Worksheets("Export 09-41-07").Sort.SortFields.Clear
    ActiveWorkbook.Worksheets("Export 09-41-07").Sort.SortFields.Add2 Key:= _
        Range("D2:D21"), SortOn:=xlSortOnValues, Order:=xlDescending
    With ActiveWorkbook.Worksheets("Export 09-41-07").Sort
        .SetRange Range("A1:D21")
        .Header = xlYes
        .Apply
    End With
    Columns("A:D").Select
    Selection.Columns.AutoFit
    Range("A1").Select
End Sub

What you are looking at

  • Every action arrives as a pair: Select something, then do it to Selection. Half the lines exist only to move the cursor.
  • The recorder writes every property of a dialog it touched, not the one you changed — hence PatternColorIndex and TintAndShade with fourteen decimal places.
  • A2:A21 is burnt in. Next week's export has 300 rows and you will format the first twenty of them.
  • The sheet name is burnt in too, so the macro is tied to the tab you happened to be on.

The same job, written

Nothing has been added below beyond a check that you are on the right sheet. The same operations, addressed instead of selected, and sized from the data instead of from the day you recorded:

Option Explicit

Sub FormatExport()
    Dim ws As Worksheet
    Dim lastRow As Long

    Set ws = ActiveSheet

    If ws.Range("A1").Value <> "date" Then
        MsgBox "Run MakeDemoExport first, then run this with that sheet in front.", _
            vbExclamation, "Wrong sheet"
        Exit Sub
    End If

    lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row

    With ws.Range("A1:D1")
        .Font.Bold = True
        .Interior.Color = RGB(226, 232, 240)
    End With

    ws.Range("A2:A" & lastRow).NumberFormat = "dd mmm yyyy"
    ws.Range("D2:D" & lastRow).NumberFormat = "#,##0.00"

    ws.Range("A1:D" & lastRow).Sort _
        Key1:=ws.Range("D1"), Order1:=xlDescending, Header:=xlYes

    ws.Columns("A:D").AutoFit

    MsgBox "Formatted " & (lastRow - 1) & " rows.", vbInformation, "Done"
End Sub

The trap: your macro is not in the file you sent

The Store macro in box offers Personal Macro Workbook, and it sounds like the sensible choice. It puts the macro in a hidden workbook called PERSONAL.XLSB that only exists on your machine. The macro then works in every file you open, which is exactly why nobody notices: you test it, you email the workbook to a colleague, and for them the button does nothing at all. The reverse also bites — a colleague's file that runs perfectly for them, because their Personal workbook holds the half of the code you never received.

Record in short bursts, one operation each. Ten small snippets you can read beat one long recording nobody can untangle — and when Excel asks on the way out whether to save changes to the Personal Macro Workbook, that is your reminder of where the last recording actually went.

How it goes on

The next lesson deals with absolute and relative recording, which is why one recording writes into A2 forever and another follows the cursor. After that comes reading generated code properly, then the case against Select, With blocks, and a full step-by-step rewrite of a recording like the one above. The course closes with the recorder's real long-term use: not making macros, but looking up the name of a property you cannot remember.

You have a weekly export that lands in Excel looking the same every time: a header row in plain text, dates that show as five-digit numbers, amounts with too many or too few decimals, rows in no useful order and columns too narrow to read. Every Monday you fix it by hand. It takes four minutes, you make a small mistake about once a month, and you have the vague feeling that Excel should be able to do this for you. It can, and the Macro Recorder is the way in.

This lesson is for Excel users who have never written a line of VBA, and for people who have recorded a macro or two and been disappointed when it broke the following week. You will record a real clean-up, read the code Excel writes, understand why that code is fragile, and see the same job written so that it works on next week's export as well. You need Excel for Windows or Mac with the Developer tab, nothing else.

The example is the one in the free lesson above: the MakeDemoExport macro builds a small untidy export with 20 rows of fictional February 2026 sales (date, customer, units, amount), and you clean it up twice, once with the recorder and once with written code. All names and numbers are made up for practice.

What the Macro Recorder really does

The recorder is a translator that sits between you and the workbook. While it runs, every action you take in the Excel window is turned into a line of Visual Basic for Applications (VBA) and written into a module, a plain text container for code inside the workbook. Bold a row and it writes Selection.Font.Bold = True. Format a column and it writes Selection.NumberFormat = "dd mmm yyyy". When you stop recording, you have a procedure, a block of code between Sub Macro1() and End Sub, that repeats those steps when you run it.

That sounds like the whole story, and for very simple jobs it is. The catch is that the recorder writes down what you did, not what you meant. You meant "format the amount column". You did "click D2, drag to D21, open Format Cells, pick a number format". So the recording says Range("D2:D21").Select followed by a format on the selection, and next week, when the export has 300 rows, it still formats exactly 20 of them. It also cannot record decisions. If you looked at the data, noticed it was the wrong sheet and switched tabs, the recording contains the switch but not the reason.

Seen this way, the recorder is two tools in one. For a beginner it is a teacher that shows how every action is expressed in code, without any syntax to learn first. For someone who already writes VBA it is a dictionary: record a step once, read the property name, then write it properly. What it is not is a finished macro. The rest of this article is about the gap between the two.

Worked example: the export before and after

Run MakeDemoExport from the lesson and you get a new sheet called Export plus the time, for example Export 09-41-07. Row 1 holds the headers date, customer, units, amount. Rows 2 to 21 hold 20 sales: one per day from 1 to 20 February 2026, customers called Customer A to Customer T, units calculated as 5 + (i Mod 7) and amounts as 149.5 * i. The job is to bold and colour the header, show column A as a date, give column D two decimals, sort by amount from largest to smallest and autofit the columns. Here are the first five rows after the clean-up:

Demo export after the clean-up, sorted by amount descending. Number formats: dd mmm yyyy in column A and #,##0.00 in column D.
Rowdate (A)customer (B)units (C)amount (D)
220 Feb 2026Customer T112,990.00
319 Feb 2026Customer S102,840.50
418 Feb 2026Customer R92,691.00
517 Feb 2026Customer Q82,541.50
616 Feb 2026Customer P72,392.00
……………
2–2120 rows163 in total31,395.00 in total

The units for Customer T are 11 because 20 Mod 7 is 6, and the amount is 149.5 × 20 = 2,990. If you want to check the totals in the sheet itself, =SUM(C2:C21) returns 163 and =SUM(D2:D21) returns 31,395. Both totals are the same before and after sorting, which is a quick way to confirm that the sort moved whole rows and did not scramble one column against the others.

Record the clean-up and Excel produces Macro1, the 32-line procedure shown in the lesson. Take away the Sub and End Sub lines and the four comment lines and one blank line the recorder adds at the top, and 25 working lines remain. Sorting them by what they actually do is the most useful exercise in this whole topic:

Macro1: what its 25 working lines do0246810Select statements6Untouched defaults3Formatting work8Sort block8
Six of the 25 working lines only move the cursor, and three set properties you never touched. Line counts are from the Macro1 recording in the lesson; your own recording may differ by a line or two depending on how you clicked.

Only 16 lines do the job, and eight of those belong to the sort block, which the recorder always writes in its long form with SortFields.Clear, SortFields.Add2, SetRange, Header and Apply. The three untouched defaults, .Pattern, .PatternColorIndex and .PatternTintAndShade, appear because you opened the fill colour menu, and the recorder writes every property on that menu, not only the one you changed. That is also where .TintAndShade = 0.799981688894314 comes from: it is the recorder's way of writing the light colour you picked from the theme palette.

Now compare the recorded lines with the written version, FormatExport, line by line:

Every recorded action and its written equivalent
Recorded in Macro1Written in FormatExportWhat changed
Rows("1:1").Select then Selection.Font.Bold = TrueWith ws.Range("A1:D1") … .Font.Bold = TrueAddressed directly, no Select, only the four header cells
Five-line With Selection.Interior block.Interior.Color = RGB(226, 232, 240)One property, an exact colour
Range("A2:A21").Selectws.Range("A2:A" & lastRow)Last row measured, not burnt in
Worksheets("Export 09-41-07").Sort… (8 lines)ws.Range("A1:D" & lastRow).Sort Key1:=ws.Range("D1"), Order1:=xlDescending, Header:=xlYesNo sheet name, one statement
Columns("A:D").Select then Selection.Columns.AutoFitws.Columns("A:D").AutoFitAddressed directly
Range("A1").Select(nothing)Only moved the cursor back

The key line in the written version is lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row. It starts at the very last row of column A and jumps up to the last filled cell, exactly like pressing Ctrl+Up from the bottom of the sheet. On the demo export it returns 21, so the formats go to A2:A21 and D2:D21, just like the recording. The difference shows up the week the export grows:

Rows formatted as the export growsData rows in the export (FormatExport covers all)Rows Macro1 formats08016024032020-row export80-row export150-row export300-row export
Example export sizes. The recording formats and sorts rows 2 to 21 forever, because those addresses are typed into its code. The written version measures the last row on every run.

With an 80-row export the recording leaves 60 rows unformatted and sorts only the first 20 rows among themselves, so the largest amount can sit anywhere below row 21 while the sheet looks sorted at first glance. With 300 rows it gets 280 rows wrong. And once the tab Export 09-41-07 no longer exists, the sort lines stop with run-time error 9, subscript out of range, because the recorder typed that exact tab name into the code.

Step by step: record, read and rewrite in Excel

  1. Show the Developer tab. On Windows: File → Options → Customize Ribbon, tick Developer in the right-hand list, OK. On a Mac: Excel → Preferences (or Settings) → Ribbon & Toolbar, tick Developer. You only do this once.
  2. Build the practice data. Press Alt+F11 (on a Mac Opt+F11 or Developer → Visual Basic), choose Insert → Module, paste MakeDemoExport from the lesson, click inside it and press F5. Close the editor and look at the new sheet.
  3. Start recording. Developer → Record Macro, or the small record button in the status bar at the bottom left. Name it Macro1 (names cannot contain spaces), leave the shortcut empty and set Store macro in to This Workbook. Click OK. Everything you do from now on is being written down, including mistakes.
  4. Do the job once, calmly. Select row 1, press Ctrl+B and pick a light fill colour. Select A2:A21, press Ctrl+1 and choose a custom format dd mmm yyyy. Select D2:D21 and choose #,##0.00. Select A1:D21, Data → Sort, sort by amount, Largest to Smallest, with My data has headers ticked. Select columns A:D and double-click a column border to autofit. Click A1.
  5. Stop recording. Developer → Stop Recording or the square button in the status bar. Forgetting this is common: the recorder keeps writing until you stop it.
  6. Read the code. Press Alt+F11, open the module the recorder created (usually Module2 if you pasted the demo into Module1) and compare each line with what you remember doing. Mark the Select lines and the defaults you never touched.
  7. Test the recording on new data. Run MakeDemoExport again to get a fresh sheet, stay on it and run Macro1 with Alt+F8, select, Run. Watch it fail on the burnt-in sheet name or work on the old tab.
  8. Paste the written version. Add FormatExport from the lesson to a module, go to the fresh export sheet and run it. The message box reports Formatted 20 rows.
  9. Step through it. Click inside FormatExport and press F8 repeatedly. Each press runs one line and highlights the next in yellow, so you can switch to the sheet and watch each change appear.
  10. Save as macro-enabled. File → Save As, file type Excel Macro-Enabled Workbook (*.xlsm). A normal .xlsx file cannot hold code, and Excel will warn you that the macros will be removed if you try.

From recording to a macro you can keep1 Recordone short task2 ReadAlt+F11, line by line3 Rewriteno Select, last row4 Keepsave as .xlsmSteps 2 and 3 are where the recording turns into a macro.
The recorder only does step 1. Reading and rewriting are what turn the recording into something you can run next month.

The finished macro, ready to paste, is this one. It is the same code as in the lesson, and it is safe to run on the demo sheet as often as you like:

Option Explicit

Sub FormatExport()
    Dim ws As Worksheet
    Dim lastRow As Long

    Set ws = ActiveSheet

    If ws.Range("A1").Value <> "date" Then
        MsgBox "Run MakeDemoExport first, then run this with that sheet in front.", _
            vbExclamation, "Wrong sheet"
        Exit Sub
    End If

    lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row

    With ws.Range("A1:D1")
        .Font.Bold = True
        .Interior.Color = RGB(226, 232, 240)
    End With

    ws.Range("A2:A" & lastRow).NumberFormat = "dd mmm yyyy"
    ws.Range("D2:D" & lastRow).NumberFormat = "#,##0.00"

    ws.Range("A1:D" & lastRow).Sort _
        Key1:=ws.Range("D1"), Order1:=xlDescending, Header:=xlYes

    ws.Columns("A:D").AutoFit

    MsgBox "Formatted " & (lastRow - 1) & " rows.", vbInformation, "Done"
End Sub

Three habits are visible in those lines. Option Explicit at the top forces every variable to be declared with Dim, so a typo becomes an error instead of a silent bug. Set ws = ActiveSheet captures the sheet once, and every later line starts with ws., so nothing depends on where the cursor is. And the guard at the top checks cell A1 before anything is changed, because a macro that formats the wrong sheet cannot be undone with Ctrl+Z: running a macro clears Excel's undo list.

Where your recording is stored, and why it matters

The Store macro in box has three options. This Workbook puts the code inside the file you are working on, so it travels with the file when you email it. New Workbook opens a fresh file for the code, which is rarely what you want. Personal Macro Workbook puts the code into a hidden file called PERSONAL.XLSB that Excel opens in the background every time it starts on your computer. Macros stored there work in every workbook you open, which is perfect for personal tools such as a shortcut that formats any selection as currency.

It is the wrong home for anything that must work for someone else. The colleague who receives your file gets the workbook without the code, and the button you attached to the macro does nothing for them. When Excel asks, as you close it, whether you want to save changes to the Personal Macro Workbook, that question is a useful reminder of where the last recording went. If you want to move a macro from there into a file, open PERSONAL.XLSB in the editor's Project Explorer, copy the procedure and paste it into a module of the workbook that needs it.

Macro Recorder and Cleanup course: recording a macro in Excel and rewriting the generated VBA code
The Macro Recorder & Cleanup course: record what Excel does, read the code, then rewrite it into a macro that survives next week.

Common mistakes and how to spot them

  • Trusting the recording without reading it. The macro ran once, on the data it was recorded on, so of course it worked. Spot it: run the recording on a copy of the data with more rows. If anything below the old last row is untouched, the addresses are burnt in.
  • Hard-coded ranges such as A2:A21. They describe the day you recorded, not your data. Spot it: search the module for addresses with row numbers (Ctrl+F in the editor) and replace them with ranges built from a measured last row.
  • A burnt-in sheet name. Recordings that sort or filter almost always contain Worksheets("…") with the tab you were on. Spot it: run-time error 9, subscript out of range, on a sort line.
  • Relative references switched on by accident. The Use Relative References button stays on between recordings. Spot it: the code is full of ActiveCell.Offset(…) and the result depends on which cell was selected when you started.
  • Recording into the Personal Macro Workbook. Spot it: the macro works on your machine and nowhere else, or the file you send contains no module at all.
  • Saving as .xlsx. Excel warns that the VB project will be lost. If you click Yes, the code is gone from that file. Spot it: the file icon and extension; macros live only in .xlsm, .xlsb or .xls files.
  • Recording scrolls and clicks you did not mean. Lines such as ActiveWindow.SmallScroll Down:=12 or a stray Range("F7").Select are harmless but noisy. Spot it: any line you cannot explain by something you meant to do can usually be deleted.
  • Expecting Ctrl+Z to rescue you. Running a macro clears the undo list. Spot it before it hurts: test every new macro on a copy of the workbook or on demo data, never on the only copy of a real report.

Quick reference: recorder, editor and the VBA used here

Shortcuts are for Excel on Windows. On a Mac, most work with Fn or Opt, and the Developer tab offers the same buttons.
ItemWhere or howWhat it does
Record MacroDeveloper → Record Macro or the status bar buttonStarts writing your actions as VBA
Use Relative ReferencesDeveloper, next to Record MacroRecords movements (Offset) instead of fixed addresses
Stop RecordingDeveloper → Stop RecordingEnds the recording
Macros dialogAlt+F8Lists, runs, edits and deletes macros
VBA editorAlt+F11Opens the code; Insert → Module adds a module
Run / stepF5 / F8Runs the procedure under the cursor / one line at a time
Format CellsCtrl+1Number formats such as dd mmm yyyy and #,##0.00
Option ExplicitFirst line of a moduleForces every variable to be declared
Cells(Rows.Count, 1).End(xlUp).RowQualified with the sheet: ws.Cells(ws.Rows.Count, 1)Last filled row in column A
Range.SortKey1:=…, Order1:=xlDescending, Header:=xlYesSorts a range in one statement
Columns("A:D").AutoFitOn a sheet objectFits column widths to the contents
Macro-enabled fileFile → Save As → .xlsmThe file type that keeps the code

Real-world uses

  • Monthly ledger exports. An accounting system writes a CSV with dates as text and amounts without separators. A cleaned-up recording formats, sorts and totals it in a second, every month, however many lines there are.
  • Standard report formatting. A finance team wants every report with the same header colour, number formats and column widths. Record the formatting once, rewrite it to work on the active sheet, and store it in the Personal Macro Workbook as a personal tool, or in a shared .xlsm for the team.
  • Learning the name of a property. You want to freeze panes, add a filter or set the print area in code and cannot remember how. Record yourself doing it once, read the line, delete the recording. This is the recorder's most valuable long-term use.
  • Preparing data for a pivot table. Removing blank rows, converting a range into a table and naming it are repetitive steps that a recording captures well, as long as you replace the fixed ranges afterwards.
  • Handing over a routine. A colleague goes on holiday and you inherit their Monday task. Recording them doing it once gives you a written, exact list of steps, even before anyone turns it into a proper macro.

What you will build in the rest of this course

This first lesson is free. Lessons 2 to 8 are part of the full course, a one-time purchase of $9.90, and they take the recording you just made all the way to a macro you can trust.

Absolute and Relative Recording. You record the same steps with the Use Relative References toggle off and on, see why one version writes into A2 forever and the other follows the cursor, and learn which one fits which task.

Reading the Generated Code. You take a typical recording apart line by line: objects, properties, methods and arguments, which lines are noise and which carry the actual work, so that any recording becomes readable in a minute.

Why Select and Activate Are Bad. You remove every Select and Selection from a recording, address ranges directly and see why the result is shorter, faster and no longer depends on where the user clicked.

With Blocks and Variables. You name an object once with With or a Worksheet variable and let every following line use it, which is what makes FormatExport above so compact.

Rewriting a Recording, Step by Step. You take a twelve-line real recording and rewrite it in a fixed order: remove noise, remove Select, qualify every range, measure the data, add a guard. The same recipe works on any recording you make afterwards.

Making It Fast and Safe. You switch off screen updating, automatic calculation and events while the macro works, and make sure they are always switched back on, even when something goes wrong halfway.

Using the Recorder as a Lookup Tool. You learn to use the recorder the way experienced VBA developers do: record one action, read the property name, throw the recording away and write the line yourself.

Summary

The Macro Recorder turns your clicks into VBA, which makes it the quickest way to learn how Excel actions look in code. Its output is a first draft: it selects before it acts, writes properties you never changed and burns in the exact ranges and sheet names of the day you recorded. In the demo export, only 16 of 25 working lines do the job, and the recording formats exactly 20 rows no matter how big the export gets. The written version addresses ranges directly, measures the last row with End(xlUp), sorts in one statement and checks it is on the right sheet first.

Try it now in the lesson above: run MakeDemoExport, record your own clean-up, read what Excel wrote and compare it with FormatExport. Then answer the check question about the Personal Macro Workbook, the one trap that catches nearly everyone the first time they share a macro.

Frequently asked questions

How do I record a macro in Excel?

Show the Developer tab, click Developer, Record Macro, give the macro a name and choose where to store it, then do the steps you want to repeat. Click Stop Recording when you are done, and run the macro later with Alt+F8.

Why does my recorded macro only work on the original data?

The recorder writes the exact cell addresses and sheet names you used, such as A2:A21. When the data has more rows or the sheet has a different name, the macro formats the old range or stops with an error, so replace fixed addresses with a measured last row.

Where are recorded macros stored?

In a module of the workbook you chose in the Store macro in box: This Workbook, a new workbook or the hidden Personal Macro Workbook (PERSONAL.XLSB). Only macros stored in This Workbook travel with the file when you send it.

Can I undo a macro in Excel?

No. Running a macro clears Excel's undo list, so Ctrl+Z cannot reverse its changes. Test new macros on a copy of the workbook or on demo data first.

Why should I remove Select from recorded VBA?

Select only moves the cursor, which makes the macro slower and dependent on what is selected when it starts. Addressing ranges directly, for example ws.Range("A1:D1").Font.Bold = True, does the same work in one line.

What file type do I need to save a macro?

Save the workbook as an Excel Macro-Enabled Workbook (.xlsm), or as a binary .xlsb file. A normal .xlsx file cannot contain VBA, and Excel removes the code if you save in that format.

Keep going: Macro Recorder & Cleanup

This free lab is lesson 1 of 8. Unlock the other 7 hands-on labs, the final exam and your certificate for a one-time $9.90.

  1. Absolute and Relative Recording
  2. Reading the Generated Code
  3. Why Select and Activate Are Bad
  4. With Blocks and Variables
  5. Rewriting a Recording, Step by Step
  6. Making It Fast and Safe
  7. Using the Recorder as a Lookup Tool

Buy course — $9.90 See the full course

Knowledge check

You record a macro with Store macro in: Personal Macro Workbook and email the workbook to a colleague. What do they get?

Continues in this course
  • Absolute and Relative Recording
  • Reading the Generated Code
  • Why Select and Activate Are Bad
  • With Blocks and Variables
  • Rewriting a Recording, Step by Step
  • Making It Fast and Safe

Buy the course to unlock the remaining 7 lessons, the exam and the certificate.

Buy course — $9.90