Excel Macro Programming: What It Is and How It Works

VBA & macros · Updated November 14, 2026

Excel macro programming means creating instructions that automate tasks in a workbook, most commonly with Visual Basic for Applications (VBA). You can record a sequence of actions or write VBA code yourself; either way, a macro can repeat routine work, but it needs a macro-capable desktop version of Excel to run.

What Excel macro programming means

A macro is a saved set of actions that Excel can perform again on demand. Examples include applying a standard report layout, cleaning imported data, creating worksheets from a template, or preparing a workbook for distribution. A macro can save time when the same reliable sequence is repeated often, especially when the steps involve several commands or workbooks.

VBA is the programming language traditionally used to create and control Excel macros. It can work with cells, ranges, worksheets, charts, tables, and many parts of the Excel application. A macro might simply bold a header row, or it might use conditions and loops to process many records. The term “macro” often refers to the saved automation, while “VBA” refers to the code behind it.

Macros are different from formulas. A formula recalculates a result as its inputs change; a macro performs actions when someone runs it or when an event triggers it. For instance, a formula can calculate a sales total, while a macro could format the report, create a dated copy, and prepare it for printing.

How a macro works

When Excel runs a VBA macro, it follows instructions in order. The code can refer to a particular worksheet or range, read values, make decisions, repeat a task, and change workbook content. For example, a loop can check each row in a list and highlight records that meet a condition. The macro runs with the permissions available to the workbook and user, so code from an untrusted source should not be treated as harmless.

The Visual Basic Editor is where you view and edit VBA. In Excel for Microsoft 365 on Windows, open it from Developer > Visual Basic or press Alt+F11. If the Developer tab is hidden, use File > Options > Customize Ribbon, select Developer under Main Tabs, and choose OK. On Mac, VBA is available in the desktop app; the Visual Basic command is on the Developer tab, and Option+F11 commonly opens the editor (some keyboards also require Fn). Excel for the web does not create, edit, or run VBA macros.

VBA code is stored in a workbook module, a worksheet module, or another code module, depending on what it needs to do. A simple macro can be started manually from the Macros dialog or attached to a button. More advanced macros can respond to events, such as opening a workbook or changing a cell, which makes careful design and testing especially important.

Recording a macro in Excel

The macro recorder is a practical starting point for beginners because it translates many ribbon actions into VBA. It is useful for learning how Excel represents a task, but the generated code can be more detailed or less flexible than code written by hand. To record a basic macro on Windows:

  1. Save a copy of the workbook, then open Developer > Record Macro.
  2. Enter a clear macro name without spaces. Optionally assign a shortcut and choose where to store the macro.
  3. Perform only the actions you want repeated. If you need the macro to work relative to the active cell rather than fixed addresses, enable Use Relative References before recording.
  4. Choose Developer > Stop Recording when finished.
  5. Use Developer > Macros to select the macro and run it on a suitable test copy.

During recording, Excel captures supported actions, not your intention. If you click the wrong cell or use an absolute reference when you meant a relative one, the resulting macro may repeat that mistake. Keep a recording short, inspect its code in the Visual Basic Editor, and test it on representative data. The recorder is less suitable for tasks that depend on changing conditions, variable-sized datasets, or decisions that need explicit logic.

A small VBA example

This example assumes a report begins in cell A1, has its headers in the first row, and forms one contiguous block of data with no blank rows or columns splitting it. It makes the header row bold and adjusts the width of the columns in that block. In the Visual Basic Editor, insert a standard module with Insert > Module and place the code there.

Option Explicit

Sub FormatReport()
    Dim ws As Worksheet
    Dim dataRange As Range

    ' Work on the active sheet; A1 must contain the report header.
    Set ws = ActiveSheet
    If IsEmpty(ws.Range("A1").Value) Then
        MsgBox "Cell A1 is blank; no report was formatted.", vbExclamation
        Exit Sub
    End If

    Set dataRange = ws.Range("A1").CurrentRegion
    dataRange.Rows(1).Font.Bold = True
    dataRange.Columns.AutoFit
End Sub

To try it, return to Excel, select a test sheet that matches the stated layout, and run FormatReport from Developer > Macros. The code acts on the active sheet, so selecting the wrong sheet can affect the wrong report. Save a separate copy before running any macro: macro changes cannot be reversed with Ctrl+Z, and the Mac equivalent shortcut, Command+Z, does not undo them either.

Choosing between VBA and other automation

VBA is often a good fit when a process already happens in desktop Excel, must interact with workbook objects, or needs to support existing macro-enabled files. It can automate a wide range of Excel operations, but it is tied to the desktop application and can require maintenance as workbooks and processes change.

  • Formulas: Best for calculations and results that should update automatically when inputs change. They are visible in the grid and usually easier to audit than a procedure that changes cells.
  • Power Query: Often better for repeatable importing, cleaning, combining, and reshaping of data. It records transformation steps without requiring VBA, though it is not a general replacement for macros that control workbook actions.
  • Office Scripts: A TypeScript-based option for automating supported Excel tasks, particularly in web-based and collaborative workflows. Availability and integration depend on the account, platform, and organization settings.
  • Manual steps: Sensible when a task is rare, short, or too variable to automate safely. Automation has a design and testing cost of its own.

Choose based on the job, not simply on which tool sounds more advanced. If the goal is to calculate a value, start with a formula. If it is to clean a recurring data import, assess Power Query. If it is to carry out a sequence of workbook actions or support an established VBA workflow, a macro may be appropriate.

Saving and sharing macro-enabled workbooks

A standard .xlsx workbook cannot store VBA project code. To keep workbook macros, save the file as an Excel Macro-Enabled Workbook (*.xlsm) using File > Save As. Excel also supports macro-enabled binary workbooks (.xlsb) and macro-enabled templates (.xltm), but those formats serve different file or template needs. Changing a macro-enabled file to .xlsx removes the VBA project, so do not use that format if the code must be retained.

When sharing a macro-enabled workbook, tell recipients what the macro does, what data it changes, and which Excel desktop environment it requires. Some organizations restrict macros through administrative policy. A recipient may be unable to run a macro even if the file itself opens normally, and Excel for the web will not run its VBA code. Consider whether recipients actually need the automation or only need a finished, macro-free report.

There is generally no separate charge for writing VBA beyond having access to a compatible desktop version of Excel, but licensing, organizational policies, and the time needed to develop and maintain code still matter. A complicated macro can cost more to support than the manual process it replaces, especially if only one person understands it.

Macro security and safe use

VBA can modify or delete workbook data and can interact with other Office features. Treat downloaded or emailed macro-enabled files with caution, particularly when the source or purpose is unclear. Windows versions of Office may block macros in files identified as coming from the internet, and organization policies can impose further restrictions. Do not bypass a warning merely to make a file run.

Excel’s macro settings are available on Windows under File > Options > Trust Center > Trust Center Settings > Macro Settings. The safest choice depends on your organization’s policy and workflow; enabling all macros is not a sound general recommendation. If a macro is needed, obtain it from a trusted source, inspect its purpose, and ask an administrator or knowledgeable reviewer when unsure. Developers can also digitally sign VBA projects, allowing recipients to verify the publisher when the signing certificate is trusted.

Before running code, keep an untouched backup and test on a copy with sample data. Be especially careful with macros that delete rows, overwrite files, send messages, or refer to external locations. A macro may run quickly and affect many records, so a small test is more useful than discovering a problem in the only copy of an important workbook.

Common problems and good practices

A macro that works on one computer may fail elsewhere because it refers to a specific file path, sheet name, or workbook state. Recorded macros can also rely on whichever cell was selected at the time. Other common causes include a missing reference, a renamed worksheet, a protected sheet, or a difference between desktop Excel and the web app. When troubleshooting, note the exact error, identify the line highlighted by the editor, and check the workbook layout and permissions the code assumes.

Make automation easier to maintain by using descriptive macro names, declaring variables, adding brief comments, and keeping procedures focused. Avoid relying on selections when code can refer directly to a worksheet and range. Document assumptions such as required sheet names, header rows, and input formats. Test normal cases as well as empty, incomplete, or unusually large datasets, and keep a known-good version of both the workbook and its code.

Frequently Asked Questions

Is Excel macro programming the same as VBA?
Not exactly. A macro is an automation task saved for Excel to run; VBA is the language commonly used to write that task. The macro recorder can create VBA code, and a person can also write or edit the code directly.

Can I run Excel macros in a browser?
No. Excel for the web can open and edit many workbooks, but it cannot create, edit, or run VBA macros. Open a macro-enabled workbook in a compatible desktop version of Excel to use its VBA automation.

Do I need to know programming to record a macro?
No. The recorder can capture many straightforward actions without requiring you to write code. Basic VBA knowledge becomes useful when you need to inspect the recording, handle variable data, add conditions, or make a macro easier to reuse.

Why did saving my workbook remove the macro?
The workbook may have been saved as .xlsx, which does not retain VBA project code. Save a workbook containing macros as .xlsm, or use another macro-capable format when it fits the task.

Can I undo a macro with Ctrl+Z?
Usually not. Running VBA clears Excel’s normal undo history, so Ctrl+Z cannot reverse the macro’s changes. Keep a backup and test code on a copy before using it on important data.

Related

Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.

More in VBA & macros

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.