Create a Macro in Excel: Record, Write VBA, and Automate Tasks

Create a macro in Excel using Record Macro or VBA. Step-by-step: record actions, write Sub code, save as .xlsm, automate repetitive tasks fast.

Microsoft ExcelBy Katherine LeeMay 27, 202613 min read
Create a Macro in Excel: Record, Write VBA, and Automate Tasks

What Is a Macro in Excel?

If you've ever caught yourself doing the same thing in Excel over and over — formatting a table, cleaning up imported data, copying rows to a new sheet — you're a prime candidate for macros. A macro is a saved sequence of actions Excel can replay on demand. Run it once, and Excel does the work in seconds instead of minutes.

Creating a macro in Excel doesn't require a computer science degree. There are two paths: you can record your actions and let Excel write the code, or you can write VBA (Visual Basic for Applications) code directly. Both methods produce the same result — an automated routine stored in your workbook. Recording is faster to set up. Writing VBA opens the door to logic, conditions, and dynamic behavior that recording alone can't handle.

Under the hood, every Excel macro is a VBA program. When you use the recorder, Excel translates your mouse clicks and keystrokes into VBA automatically. So even if you start with recording, peeking at the generated code is a great way to learn VBA syntax without starting from scratch. The gap between recording and coding is smaller than it looks.

This guide walks you through both approaches in detail. You'll also learn how to save macro-enabled files, manage security settings, assign macros to buttons, and put automation to work on tasks you actually care about. Whether you're new to automation or just need a refresher on Excel features you haven't used in a while, this covers it step by step.

Macros pair especially well with other Excel capabilities. If you're automating data analysis in Excel, a macro can handle the repetitive prep work — cleaning columns, applying consistent formatting, merging sheets — so your analysis starts from a clean, predictable state every time. Think of macros as the invisible assistant that preps everything before the real work begins.

Method 1: Record a Macro

Recording is the starting point for most people. You don't need to know a single line of code. Excel literally watches what you do and saves it as replayable code.

Here's a real-world example. Say you get a weekly CSV export from your CRM, and every week you spend five minutes applying the same column widths, bold headers, and filter settings. That's exactly the kind of task recording was built for. Do it once while Excel is watching, and you'll never do it manually again.

Go to the View tab on the ribbon and click Macros → Record Macro. If you have the Developer tab enabled, click Developer → Record Macro — same dialog either way. Inside it, give the macro a name with no spaces (use underscores or camelCase: FormatWeeklyReport, not Format Weekly Report). Optionally assign a shortcut key like Ctrl+Shift+W. Choose where to store it: This Workbook (this file only), Personal Macro Workbook (all your files), or New Workbook. Click OK — recording has started.

Perform every action you want automated. Format cells, enter data, apply filters, navigate sheets — Excel records all of it. When you're done, stop recording via View → Macros → Stop Recording or click the Stop button in the status bar. To run the macro: View → Macros → View Macros → select it → Run. Or press the shortcut you assigned.

By default, recording captures absolute references — if you clicked B3 during recording, the macro always goes to B3. If you want the macro to act relative to your current position, toggle on Use Relative References under View → Macros before you start. It's especially useful for macros that process each row in a dataset one at a time.

Microsoft Excel - Microsoft Excel certification study resource

Step-by-Step: Record a Macro

  1. View tab → Macros → Record Macro (or Developer → Record Macro).
  2. Set the macro name (no spaces), optional shortcut key, and storage location.
  3. Click OK — Excel is now recording every action.
  4. Perform all the actions you want to automate.
  5. View → Macros → Stop Recording (or the Stop button in the status bar).

Running the Macro

  • Ribbon: View → Macros → View Macros → select → Run.
  • Keyboard shortcut: Press the Ctrl+Shift+[letter] you assigned.
  • Sheet button: Assign to a form control or shape (see Assigning section).

Tip — Relative vs Absolute: Enable Use Relative References (View → Macros) before recording if you want the macro to follow your cursor, not always target the same fixed cells.

Method 2: Write VBA Code Directly

Recording handles simple tasks well, but it can't make decisions, loop through a variable number of rows, or ask the user for input. Writing VBA directly solves all of that — and it's more powerful than most people expect. If you've only ever used Excel's built-in functions, VBA opens an entirely different dimension of what's possible.

The first thing you need is the Developer tab. If it's not visible, go to File → Options → Customize Ribbon, check Developer on the right, and click OK. The tab appears immediately — no restart needed.

From the Developer tab, click Visual Basic to open the VBA editor. You can also press Alt+F11 from anywhere in Excel. The editor has its own window — a Project Explorer on the left listing all open workbooks and their components, and a code pane in the center where you write your programs.

To add a macro, right-click your workbook in the Project Explorer → Insert → Module. A blank module appears. Every macro lives inside a Sub ... End Sub block. The name follows the Sub keyword; code goes in between. Comments start with an apostrophe (') and are ignored at runtime — use them freely to document what each section does.

A few VBA patterns worth knowing early. Range("A1").Value = "Hello" puts text in a cell. Range("A1").Font.Bold = True makes it bold. Cells(row, column) references cells by row and column numbers, which is useful in loops. Sheets("Sheet1").Activate switches to a named sheet. These building blocks combine into surprisingly capable automation.

Variables in VBA use Dim: for example, Dim i As Integer. You don't have to declare variables — VBA lets you skip it — but declaring them catches typos and improves performance. Putting Option Explicit at the top of a module forces declaration on all variables, which is a smart habit from day one.

If you want to see how recording translates clicks into code, record a simple macro and then open the VBA editor. Find the generated module and read through it. It's often verbose compared to hand-written VBA, but reading it teaches you how Excel refers to objects, properties, and methods.

Look for patterns as you read: how does Excel reference a range? How does it apply a number format or select a sheet? Every question you can answer by reading recorded code is one less concept you need to look up later. It's the fastest self-guided VBA tutorial available — and it's already built into Excel.

Excellence Playa Mujeres - Microsoft Excel certification study resource
  • Enable the Developer tab: File → Options → Customize Ribbon → check Developer
  • Open VBA editor: Alt+F11 (or Developer → Visual Basic)
  • Insert a module: right-click workbook in Project Explorer → Insert → Module
  • Write your Sub: Sub MacroName() ... End Sub
  • Run it: press F5 inside the Sub, or Alt+F8 in Excel → select → Run
  • Save as .xlsm (not .xlsx) to keep your macros

Macro Security Settings and Saving Your File

Excel doesn't run macros automatically when you open a file — and that's by design. Macros execute code on your machine, so a malicious macro in a file from an unknown source could cause real damage. Excel's security model keeps you in control.

Trust Center Settings

Configure security at File → Options → Trust Center → Trust Center Settings → Macro Settings. There are four levels:

  • Disable all macros without notification — nothing runs, no prompts. Standard in locked corporate environments.
  • Disable all macros with notification (Excel's default) — macros don't run, but a yellow security bar appears. You click Enable Content when you trust the file.
  • Disable all macros except digitally signed macros — only macros with a valid certificate run without prompting.
  • Enable all macros — everything runs automatically. Only appropriate in fully controlled, trusted environments.

For most people, the default (disable with notification) is right. You see a prompt for every macro-enabled file you open, decide whether you trust it, and proceed. For your own files you open regularly, add the folder as a Trusted Location (Trust Center → Trusted Locations) so those files skip the security bar entirely.

Saving as .xlsm

This trips up almost everyone the first time. If you save your workbook as a standard .xlsx file, Excel silently removes all macros. No warning by default — they're just gone. If you've already closed the file, there's no recovering them.

To keep macros, save as .xlsm (Excel Macro-Enabled Workbook): File → Save As → pick Excel Macro-Enabled Workbook (*.xlsm) from the dropdown. Excel does warn you if you try to save a macro-containing file as .xlsx — don't dismiss that warning. The .xlsm file looks and opens identically to .xlsx; the only difference is preserved VBA code.

The Personal Macro Workbook

Say you've built a macro for cleaning up date formats or formatting tables your preferred way. You want it in every workbook — not locked to one file. That's exactly what the Personal Macro Workbook is for.

When you record a macro and choose Personal Macro Workbook as the storage location, Excel saves the code to a hidden file called PERSONAL.XLSB in your local AppData folder. This file opens automatically every time Excel starts, invisibly in the background. Any macro stored there is available in every workbook you open on that machine.

To view or edit PERSONAL.XLSB: go to View → Unhide, select it from the list, and it surfaces as a visible workbook. Alternatively, open the VBA editor (Alt+F11) and expand the PERSONAL.XLSB entry in the Project Explorer — your code modules are right there.

One caveat: PERSONAL.XLSB lives on your machine only. It doesn't travel with shared files. If colleagues need the same macro, embed it in the shared workbook directly. You can also right-click the module in the VBA editor → Export File to produce a .bas file you can email — they import it into their own PERSONAL.XLSB. It's a quick way to share automation without sharing the whole workbook. And if you ever switch machines or do a clean OS install, don't forget to back up PERSONAL.XLSB — it won't be recreated automatically.

Macros pair naturally with features like Excel pivot tables — automate the prep and refresh cycle, then pivot for instant analysis. And if your macro includes formatting steps like how to indent in Excel, you'll save time on every polished report that goes out.

Excel Spreadsheet - Microsoft Excel certification study resource

5 Practical VBA Macro Examples

Format Header Row (Bold + Fill Color)

Sub FormatHeader() Range("A1:E1").Font.Bold = True Range("A1:E1").Interior.Color = RGB(173, 216, 230) End Sub Instantly applies bold text and a light blue fill to your header row. Adjust the range to match your table width.

Loop Through Rows and Fill Values

Sub FillNumbers() Dim i As Integer For i = 1 To 10 Cells(i, 1).Value = i Next i End Sub Fills cells A1 through A10 with 1–10. Change the bounds and column number to match your data range.

Clear a Data Range (Keep Formatting)

Sub ClearData() Range("B2:D50").ClearContents End Sub Clears values but preserves formatting in B2:D50. Good for resetting a weekly template before pasting fresh data.

Copy Data to Another Sheet

Sub CopyToSummary() Sheets("Data").Range("A1:C100").Copy _ Destination:=Sheets("Summary").Range("A1") End Sub Copies a block from the Data sheet to Summary in a single step. No manual copy-paste needed.

MsgBox with User Input

Sub GreetUser() Dim userName As String userName = InputBox("Enter your name:") MsgBox "Done, " & userName & "! Report updated." End Sub Useful for macros that need a user confirmation step or want to show a completion message when finished.

Record a Macro vs. Write VBA: Pros and Cons

Pros
  • +Recording requires zero coding knowledge — anyone can use it immediately
  • +VBA gives complete control: loops, conditionals, user prompts, dynamic ranges
  • +Recorded code doubles as free VBA tutorials — read it to learn the language
  • +Personal Macro Workbook makes automation available across every Excel file
  • +Buttons and shortcuts make macros accessible to non-technical teammates
Cons
  • Recorded macros use absolute references by default — can break on different datasets
  • VBA code isn't portable: macros don't work in Excel for Web or Google Sheets
  • Macro-enabled files (.xlsm) raise security prompts — colleagues may hesitate
  • Complex VBA logic requires debugging skills that take time to build
  • Saving as .xlsx silently deletes all macros — a common and painful mistake

Assigning Macros to Buttons, Debugging, and Best Practices

Assigning a Macro to a Button

Opening the View menu every time you run a macro gets old fast. A button directly on the sheet is cleaner — one click, and it fires. Make sure the Developer tab is visible (File → Options → Customize Ribbon → check Developer). Then go to Developer → Insert and under Form Controls, click the Button icon. Draw it on your sheet by clicking and dragging. The Assign Macro dialog opens immediately — pick your macro and click OK.

You're not limited to the plain grey button. Right-click any shape on the sheet — a rectangle, a rounded box, an arrow — and choose Assign Macro. This is common in dashboard-style sheets where polished styling matters. The shape can have any fill color, font, or border. Macro behavior is identical regardless of shape appearance.

Absolute vs. Relative Recording in Practice

When you record in absolute mode (the default), every cell reference is hard-coded. Record yourself clicking A3, and the macro always goes to A3. Good for macros that target the same fixed range every time — a header row formatter, for example.

Switch to relative mode by enabling Use Relative References (View → Macros — toggle it before you start recording). Now the macro records movement relative to your starting cell, so it works correctly wherever you position your cursor before running it. Mix both modes in one session: toggle relative on for the flexible parts, off for the fixed parts. The VBA code reflects each state accurately.

Debugging Tools in the VBA Editor

When a macro produces unexpected results or throws an error, the VBA editor's debugging tools pinpoint the problem. Open it with Alt+F11, click inside the Sub, and press F8 to step through code one line at a time — each press highlights the next instruction and runs the current one. You can watch Excel respond in real time.

Breakpoints let you run at full speed until a specific line, then pause. Click in the gray left margin next to any line to set a red dot. When you run the macro, it executes normally until that point. From there, step with F8, press F5 to continue, or use the Immediate Window (Ctrl+G) to inspect variable values by typing ? variableName and pressing Enter.

For macros you share, add error handling: put On Error GoTo ErrorHandler at the top of the Sub and a handler at the bottom (Exit Sub / ErrorHandler: MsgBox "Error: " & Err.Description). It doesn't prevent errors, but it replaces cryptic VBA crash dialogs with readable messages your colleagues will appreciate.

Shortcut Conflicts and Final Tips

When assigning shortcut keys, check for conflicts. Your macro wins over Excel's built-in shortcut if they share the same combo — meaning you lose the built-in feature. Safe choices that Excel doesn't claim by default: Ctrl+Shift+Q, Ctrl+Shift+J, Ctrl+Shift+Y. Avoid Ctrl+C, Ctrl+Z, Ctrl+S unless you're intentionally overriding them.

For operations involving row manipulation, check the keyboard shortcut to delete row in Excel before you assign a macro shortcut that might overlap with a binding you already rely on.

Creating macros in Excel for the first time feels daunting until you actually try it. Record something small, open the editor, read the code. Change one value, run it again, see what changed. That iterative loop is genuinely the fastest path to fluency — and before long, writing a Sub will feel as natural as entering a formula.

Essential Macro Keyboard Shortcuts

  • Alt+F11 — Open the VBA editor from anywhere in Excel
  • Alt+F8 — Open the Macro dialog to run, edit, or delete macros
  • F5 — Run the current Sub while inside the VBA editor
  • F8 — Step through code one line at a time (debug mode)
  • Ctrl+G — Open the Immediate Window for testing VBA expressions
  • Ctrl+Shift+[letter] — Custom shortcut you assign when creating a macro

Excel Questions and Answers

About the Author

Katherine LeeMBA, CPA, PHR, PMP

Business Consultant & Professional Certification Advisor

Wharton School, University of Pennsylvania

Katherine Lee earned her MBA from the Wharton School at the University of Pennsylvania and holds CPA, PHR, and PMP certifications. With a background spanning corporate finance, human resources, and project management, she has coached professionals preparing for CPA, CMA, PHR/SPHR, PMP, and financial services licensing exams.