Excel Macros: How to Record, Edit, and Run Them
Learn how Excel macros work, how to record your first macro, how to edit VBA code, and when macros are the right tool for automating repetitive tasks.

Excel macros are recorded or written sequences of instructions that automate repetitive tasks in a spreadsheet. When you record a macro, Excel captures each action you perform — formatting cells, entering formulas, copying and pasting data, applying filters — and translates those actions into Visual Basic for Applications (VBA) code stored inside the workbook.
Running the macro later replays those actions instantly, regardless of how many rows of data are involved. For analysts, accountants, and operations staff who perform the same multi-step transformation on data every week, macros eliminate hundreds of manual keystrokes and dramatically reduce the risk of human error in routine processes.
Macros exist in two forms: those recorded using Excel's built-in macro recorder, and those written directly in the VBA editor. Recorded macros are suitable for straightforward, linear tasks — cleaning up a downloaded report, applying consistent formatting, running a standard set of formulas.
Written VBA macros are for more complex automation: conditional logic (do X if condition Y is true), loops (do this action for every row in the dataset), user input forms, automated file saving and emailing, and dynamic range detection. Many professional automation workflows combine both approaches — recording the basic structure and then editing the resulting VBA code to add the logic that the recorder cannot capture.
The business case for macros is straightforward in any organization that runs recurring reports. Consider a finance analyst who spends 45 minutes every Monday morning downloading a sales report, cleaning it up (removing header rows, reformatting date columns, applying number formats, deleting unnecessary columns), and generating a summary tab. A well-written macro executes the same sequence in under 60 seconds. Over a year, that single macro saves more than 38 hours — nearly a full work week.
Multiplied across the dozens of similar recurring tasks that exist in most finance, operations, and HR departments, macro automation represents a substantial productivity lever. The barrier is perceived complexity: many users assume VBA programming is beyond their abilities, when in practice, the macro recorder combined with minimal editing of the resulting code handles the majority of real-world automation needs without advanced programming knowledge.
Version control for macro-enabled workbooks is an often-overlooked operational concern. Unlike worksheets and formulas which are visible and diffable, VBA code changes are invisible in standard file comparison tools. Organizations that make frequent macro modifications should export VBA modules as .bas text files to a version control system (Git works well), allowing change history and rollback capability that the binary .xlsm format cannot provide on its own.
Excel Macros Quick Reference
- Record a macro: View tab → Macros → Record Macro (or Developer tab)
- Run a macro: Alt+F8 → select macro → Run
- Open VBA editor: Alt+F11
- Macro file format: Must save as .xlsm (macro-enabled workbook)
- Security warning: Macros are disabled by default — enable only in trusted workbooks
- Keyboard shortcut: Assign Ctrl+letter when recording for one-keystroke execution
Recording your first macro requires enabling the Developer tab, which is hidden by default in Excel. To show it: right-click anywhere in the ribbon, select Customize the Ribbon, and check the Developer box in the right panel. Once visible, the Developer tab provides access to the macro recorder, the VBA editor, and form controls. Alternatively, the macro recorder is also accessible under View → Macros → Record Macro.
When you click Record Macro, a dialog asks for a name (no spaces), an optional keyboard shortcut, where to store the macro (this workbook, new workbook, or Personal Macro Workbook), and an optional description. The Personal Macro Workbook is a hidden workbook that opens automatically every time Excel starts, making its macros available in all workbooks — the right choice for utility macros you want to access everywhere. This Workbook storage means the macro is available only when that specific file is open, which is appropriate for macros that are specific to a particular report or dataset.
Once you click OK, every action you take in Excel is recorded until you stop the recorder. After recording, open the macro via Alt+F8 or the Developer tab to run it on new data. If the macro doesn't produce the right result, you can either re-record it or open the VBA editor (Alt+F11) to inspect and modify the generated code. The code is organized in modules inside the VBAProject for the workbook — double-click any module to view the Sub procedures (macros) stored there.
Viewing the generated code is the fastest way to start learning VBA, because you can see exactly how Excel translates recorded actions into instructions and begin modifying them to handle cases the recorder doesn't support, like processing a variable number of rows. The broader Excel guide covers which automation tool — macros, Power Query, or formulas — is best suited to different transformation tasks.
The For...Next loop is the single VBA construct that transforms recorded macros into genuinely powerful automation tools. A For...Next loop repeats a block of code a specified number of times — typically once for each row of data. Combined with dynamic last-row detection, it turns a macro that can only process a fixed-size dataset into one that handles any number of rows: For i = 2 To LastRow processes every row from row 2 to the last row of data.
Inside the loop, you reference each row using the loop variable — Cells(i, 1) is column A in the current row, Cells(i, 2) is column B. If...Then conditional statements within the loop allow different actions based on cell values — delete this row if column C is empty, apply red formatting if column D value exceeds a threshold, copy the row to another sheet if column B matches a criteria. These two constructs together — loops and conditionals — cover the majority of non-trivial automation use cases.

Common Excel Macro Use Cases
Apply consistent headers, fonts, column widths, number formats, and freeze panes to downloaded reports. A formatting macro converts raw exports into presentation-ready format in seconds instead of minutes. Ideal for recurring reports where the structure is always the same.
Remove blank rows, trim whitespace, standardize text case, delete specific columns, and apply TRIM/CLEAN functions automatically. Record the cleanup sequence once on a sample file, then run it on each new download without repeating the manual steps.
Insert a standard set of formula rows at the bottom of a dataset — totals, averages, percentage calculations — regardless of how many data rows exist. VBA can detect the last row dynamically so the formulas always land correctly below the data.
Loop through all files in a folder, open each one, perform a transformation, save, and close. VBA FileSystemObject enables fully automated processing of dozens or hundreds of files that would otherwise require manual open-edit-save for each.
Create a custom form with dropdown menus, text fields, and input validation that writes data to a structured table. Reduces data entry errors and enforces consistent formats without requiring users to interact directly with the worksheet cells.
Save specific sheets as PDFs, generate timestamped archive copies of reports, or trigger Outlook to email a report to a distribution list — all from a single button click. Common in finance teams distributing weekly or monthly reports.
Absolute versus relative recording is the most important concept to understand before recording your first macro. By default, the macro recorder uses absolute cell references — if you click cell A1 during recording, the macro will always go to A1 when run. This is appropriate when your data always starts in the same location, but it breaks when the starting position varies or when you want the macro to operate on whatever cell is currently selected.
To record with relative references — so the macro operates relative to wherever the cursor is at the time of execution — click Use Relative References in the Developer tab before starting the recorder. Most data processing macros benefit from relative recording, while navigation macros (always go to a specific cell to enter a date, for example) work better with absolute recording.
Understanding common VBA elements makes editing recorded macros much faster even without prior programming experience. Sub marks the beginning of a macro and End Sub marks its end — everything between these lines is the macro's code. Range("A1") refers to cell A1; Range("A1:C100") refers to that block. ActiveCell refers to the currently selected cell. Selection refers to whatever is currently selected.
Cells(row, column) is an alternative way to reference cells using numbers — Cells(1,1) is A1, Cells(2,3) is C2. With...End With groups multiple operations on the same object — if you are applying five formatting properties to the same range, wrapping them in a With block is cleaner and faster than repeating the range reference five times. These fundamentals cover 80% of what you encounter in typical recorded macro code.
Variable-length data handling is where VBA macros add the most value over recorded macros. A common pattern: find the last row of data dynamically using LastRow = Cells(Rows.Count, "A").End(xlUp).Row, then use that variable in range references — Range("B2:B" & LastRow) — so the macro operates correctly whether there are 50 rows or 50,000. The COUNTIF function in Excel can complement VBA macros by providing formula-based counts that a macro then reads and acts upon — a useful pattern for conditional automation where the macro's behavior depends on calculated values in the worksheet.
Error handling is the difference between a macro that is usable by colleagues who didn't write it and one that only works reliably for its author. When a macro encounters an unexpected condition — a file that isn't where it expects, a sheet that has been renamed, a cell that contains text where a number was expected — it throws a runtime error and halts, often leaving the workbook in a partially-transformed state.
Professional-grade macros use On Error GoTo to redirect execution to an error handler that either corrects the condition and retries, skips the problematic item and continues, or displays a descriptive message explaining what went wrong and restoring the workbook to a clean state before exiting. Adding basic error handling to a macro takes 10-15 additional lines of code and is worth every one of them for any macro that runs on real-world data from sources you do not fully control.

Macros are disabled by default in Excel because malicious VBA code embedded in workbooks is a real attack vector — historically, macro viruses were one of the most common types of malware distributed through Office files. Excel's Trust Center (File → Options → Trust Center → Trust Center Settings → Macro Settings) offers four levels: disable all macros with notification (recommended default), disable all macros without notification, disable all macros except digitally signed macros, and enable all macros.
For organizational environments, the safest approach is to digitally sign trusted macros with a code signing certificate, then set macro settings to only allow signed macros. For individual workbooks from known sources, adding them to a Trusted Location (also in Trust Center settings) allows their macros to run without repeated security prompts while maintaining protection against untrusted files.
The Personal Macro Workbook is a hidden workbook stored at %APPDATA%\Microsoft\Excel\XLSTART\PERSONAL.XLSB on Windows. Any macros stored there are available in all Excel sessions on that machine. It is the right place for utility macros you want everywhere — a macro to quickly format a selected range as a table, a macro to copy only visible cells after filtering, a macro to remove all empty rows in a selection.
Creating a collection of these utilities in the Personal Macro Workbook and assigning each a keyboard shortcut turns Excel into a customized power-user environment. The workbook is created automatically the first time you record a macro and choose Personal Macro Workbook as the storage location; it is hidden by default but can be made visible via View → Unhide if you need to edit its modules directly.
Buttons and form controls give users who are not comfortable with keyboard shortcuts a simple way to run macros. Insert a button from the Developer tab (Insert → Button), draw it on the sheet, assign a macro to it in the dialog that appears, and label it with descriptive text — Run Report, Format Data, Export PDF. Buttons can be styled to match the workbook's visual design using shape formatting.
For more polished interfaces, assigning macros to custom Quick Access Toolbar buttons (right-click the QAT and select Customize) or custom ribbon groups allows one-click macro execution from a permanent interface element rather than an embedded button on a specific sheet. The conditional formatting in Excel guide covers another Excel automation tool that, combined with macros, can create dashboards that both visually highlight data patterns and provide one-click processing controls.
Event-driven macros extend automation beyond manual execution to automatic responses to workbook events. The Workbook_Open event runs code automatically when the workbook opens — useful for refreshing data connections, checking for stale dates, or presenting a welcome message. The Worksheet_Change event fires whenever a cell value changes — enabling live validation, automatic calculations, or dependent cell updates that respond in real time without formulas.
The Workbook_BeforeSave event runs before the file saves — suitable for automatic timestamping, mandatory field validation, or generating a snapshot copy. These event procedures are written in the module associated with the specific workbook or worksheet object (not in a standard module), accessed by double-clicking ThisWorkbook or the sheet name in the VBA editor's Project Explorer. Event macros must be used carefully, as ones that trigger other changes can create recursive loops — always include a guard condition that prevents the macro from triggering itself.

Saving as .xlsx: Standard .xlsx files cannot store macros. When you save a macro-enabled workbook as .xlsx, Excel warns you that macros will be lost. Always save macro workbooks as .xlsm (Excel Macro-Enabled Workbook) or .xlsb (Binary Workbook, faster for large files).
Hardcoded ranges that break on new data: A macro that references Range("A2:A100") fails when data has 200 rows. Use dynamic last-row detection (Cells(Rows.Count, "A").End(xlUp).Row) so ranges adjust automatically to actual data size.
Not handling errors: If a macro encounters an unexpected condition — missing sheet, empty cell, wrong data type — it crashes with a runtime error. Adding On Error GoTo ErrorHandler at the top and an error handler at the bottom prevents uncaught errors from leaving the workbook in a broken state.
Opening files from macros without error handling: If a macro tries to open a file that doesn't exist or is already open, it crashes without error handling. Always check file existence before opening with Dir() and handle the open-already case.
Learning VBA for Excel macros opens capabilities that no formula can match: writing to external files, connecting to databases via ADO, automating other Office applications through inter-application automation (Excel controlling Word or Outlook), and building full data processing pipelines that would otherwise require a programming language.
The learning curve is gentler than most programming languages because VBA syntax is English-like, the development environment (the VBA editor) is built into Excel, and the recording feature lets you generate syntactically correct code for new operations simply by performing them in the spreadsheet. Most Excel power users who commit to learning VBA reach practical productivity within a few days of focused practice — recording macros, reading the generated code, making modifications, and running tests.
For complex data transformation tasks where macros are cumbersome, Power Query is often the better tool. Power Query handles importing, cleaning, reshaping, and merging data from multiple sources through a GUI interface that generates M language code — no VBA required. Power Query transformations are also refresh-able with a single click when source data updates, which gives them an advantage over one-shot macro transformations for recurring use.
The choice between macros and Power Query generally follows this rule: use Power Query for data import and transformation, use macros for automation that involves user interaction, file operations, report generation, or actions across multiple sheets or workbooks that Power Query cannot address within its data model. Combining both in a single workflow — Power Query handles the data prep, a macro handles the formatting and export — produces automation that is both robust and maintainable. The SUMIFS function overview covers formula-based summarization that often complements macro-driven data preparation workflows.
For organizations moving toward more collaborative and cloud-based workflows, the macro ecosystem has limitations that affect adoption decisions. Excel for the web does not support VBA macros — macro-enabled workbooks (.xlsm) can be stored in SharePoint and OneDrive but their macros only run in the desktop application. Microsoft is developing Office Scripts as a cloud-native alternative: JavaScript-based scripts that run in Excel for the web, can be triggered via Power Automate, and are stored in OneDrive rather than the workbook.
Office Scripts are not yet as capable as VBA for complex automation, but they represent the direction for automation in cloud-connected Excel environments. Teams that are already heavily invested in the Microsoft 365 platform and use SharePoint, Teams, and Power Automate should evaluate Office Scripts alongside VBA when building new automation, particularly if the workflows need to run without desktop Excel or as part of larger cloud-based process automations.
- +Macros can automate anything you can do manually — no UI limitation
- +VBA can interact with other Office applications and external systems
- +Macros can respond to user inputs and events (button clicks, cell changes)
- +Power Query excels at repeatable data import, cleaning, and reshaping
- +Power Query requires no coding — GUI-driven transformations
- −Macros require .xlsm format — incompatible with some email and SharePoint restrictions
- −VBA knowledge required to edit macros beyond simple recorded sequences
- −Macros are a security risk in untrusted files — disabled by default
- −Power Query cannot perform file I/O, send emails, or create interactive forms
- −Power Query M language is harder to learn than VBA for non-developers
Excel Questions and Answers
About the Author
Attorney & Bar Exam Preparation Specialist
Yale Law SchoolJames R. Hargrove is a practicing attorney and legal educator with a Juris Doctor from Yale Law School and an LLM in Constitutional Law. With over a decade of experience coaching bar exam candidates across multiple jurisdictions, he specializes in MBE strategy, state-specific essay preparation, and multistate performance test techniques.