Xls Macro Example: A Step-by-Step VBA Guide

VBA & macros · Updated November 23, 2026

An XLS macro is a VBA (Visual Basic for Applications) program stored inside an Excel workbook that automates repetitive tasks. A simple example: Range("A1").Value = "Hello" writes text into cell A1 when run. Below is a complete, working macro that formats a sales report, plus a plain-English explanation of how to build, run, and troubleshoot your own macros.

What Is a Macro and Why Use It?

Macros are essentially recorded or written instructions that Excel executes in sequence. They can do anything from inserting a row to rebuilding an entire dashboard. The main benefits are speed, consistency, and error reduction. Instead of manually formatting 50 columns, a macro does it in one click. Macros are stored in VBA modules inside the workbook file; for .xls files (Excel 97–2003) they are part of the binary format, while modern .xlsm files store them in a separate XML part.

How to Create a Simple Macro: Step-by-Step

You can create a macro two ways: record it with the Macro Recorder, or write VBA code directly. For beginners, recording is easiest, but writing code gives more control. Here’s how to write a basic macro manually:

  1. Press Alt+F11 to open the VBA editor (on Mac: Fn+Option+F11).
  2. In the Project Explorer, right-click your workbook name and choose Insert > Module.
  3. In the new module window, type the following code:
Sub FormatReport()
    ' Format a simple sales report
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Sheets("Sheet1")

    ' Add a title
    ws.Range("A1").Value = "Monthly Sales Report"
    ws.Range("A1").Font.Bold = True
    ws.Range("A1").Font.Size = 14

    ' Set column widths
    ws.Columns("A:D").ColumnWidth = 20

    ' Add a header row
    ws.Range("A2:D2").Value = Array("Product", "Units", "Price", "Total")
    ws.Range("A2:D2").Font.Bold = True

    ' Fill sample data
    ws.Range("A3").Value = "Widget"
    ws.Range("B3").Value = 5
    ws.Range("C3").Value = 10
    ws.Range("D3").Formula = "=B3*C3"

    ' Format the total column
    ws.Range("D3").NumberFormat = "$#,##0.00"
End Sub
  1. Press F5 to run the macro while the cursor is inside the code, or close the editor and run it from the Macros dialog (Alt+F8).

Save the workbook as Excel Macro-Enabled Workbook (*.xlsm) to keep the macro. If you save as .xlsx, Excel will strip the code.

Recording a Macro: The No-Code Way

If you don’t want to type VBA, use the Macro Recorder. Go to View > Macros > Record Macro (on Excel for the web, this feature isn’t available; use the desktop app). Give the macro a name, assign a shortcut key if you like, and choose where to store it (usually “This Workbook”). Then perform your actions—formatting, entering formulas, etc. Click Stop Recording. Excel writes the VBA code behind the scenes. You can then view the generated code in the VBA editor to learn from it. The recorder is great for simple tasks but often produces inefficient code, so manual editing is recommended for complex workflows.

Common Problems and How to Fix Them

Macros can fail for several reasons. Here are the most frequent issues and their solutions:

  • “Macros are disabled” error: Excel blocks macros by default for security. Go to File > Options > Trust Center > Trust Center Settings > Macro Settings and choose “Disable VBA macros with notification” (recommended) or “Enable all macros” (risky). For a single file, you can also right-click the file, choose Properties, and check “Unblock” if it came from the internet.
  • “Sub or Function not defined”: This means you misspelled a subroutine name or the code is in the wrong module. Check that the macro name matches exactly.
  • Runtime error 1004: Often caused by referencing a sheet or range that doesn’t exist. For example, if your worksheet is named “Data” but your code says “Sheet1”, change it to the actual name.
  • Macro runs too slowly: Turn off screen updating at the start of the macro with Application.ScreenUpdating = False and turn it back on at the end. This speeds up execution significantly.
  • Undo doesn’t work after a macro: Macros cannot be undone with Ctrl+Z. Always save a copy of your workbook before running a macro that modifies data.

How to Choose Between Recording and Writing VBA

Deciding which method to use depends on your task and skill level. Use the recorder when:

  • You need a quick one-time automation and don’t care about efficiency.
  • You’re learning VBA and want to see how actions translate to code.
  • The task is simple and linear (e.g., formatting a header).

Write VBA manually when:

  • You need loops, conditionals, or complex logic (e.g., iterate through rows and sum totals).
  • You want to make the macro flexible (e.g., ask the user for input).
  • You need to handle errors gracefully.
  • You plan to reuse the macro across different workbooks.

A good rule: start with the recorder, then edit the generated code to add loops or conditions.

Real-World Example: Automating Data Cleanup

Suppose you receive a weekly export with extra blank rows and inconsistent date formats. A macro can clean it in seconds. Here’s a more advanced example that removes blank rows and formats dates properly:

Sub CleanData()
    ' Clean raw data: remove blank rows and format dates
    Dim ws As Worksheet
    Dim lastRow As Long
    Dim i As Long

    Set ws = ThisWorkbook.Sheets("Sheet1")
    lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row

    ' Loop from bottom to top to avoid skipping rows after deletion
    For i = lastRow To 1 Step -1
        If ws.Cells(i, 1).Value = "" Then
            ws.Rows(i).Delete
        End If
    Next i

    ' Format column B as date (assuming dates are in column B)
    ws.Range("B2:B" & lastRow).NumberFormat = "mm/dd/yyyy"

    MsgBox "Cleanup complete!"
End Sub

This macro loops from the bottom row upward, deletes any row where column A is empty, and then formats column B as a date. The End(xlUp) method finds the last used row efficiently.

Safety and Security: What You Must Know

Macros can contain malicious code. Only enable macros from sources you trust. Always save a backup copy of your workbook before running a macro, because changes are not reversible with Ctrl+Z. Also, be aware that .xls files (old format) are more susceptible to macro viruses; modern .xlsm files are safer but still not immune. To protect your system, keep your antivirus software updated and consider digitally signing your macros with a self-signed certificate if you distribute them. If you receive a workbook with macros, examine the code in the VBA editor before enabling it—look for suspicious commands like Shell, Kill, or DeleteSetting that could harm your computer.

Frequently Asked Questions

How do I run a macro in Excel?

Press Alt+F8 to open the Macro dialog box, select the macro you want, and click Run. You can also assign the macro to a button or keyboard shortcut. To assign a shortcut, go to View > Macros > View Macros, select the macro, click Options, and enter a key combination like Ctrl+Shift+M.

What is the difference between .xls and .xlsm files?

.xls is the legacy Excel binary format (97–2003) that can store macros. .xlsm is the modern XML-based format (2007 and later) that explicitly supports macros. The .xlsx format does not store macros at all. If you save a macro-enabled workbook as .xlsx, Excel will warn you that macros will be removed.

Can I use macros in Excel for the web?

No, Excel for the web does not support VBA macros. You can view and run macros in the desktop version only. If you need to automate tasks in the browser, consider using Office Scripts, which are a different technology based on TypeScript, but they require a Microsoft 365 subscription and are not compatible with VBA.

How do I share a macro with someone else?

You can share the entire workbook (.xlsm) or export the module as a .bas file. To export, open the VBA editor, right-click the module in Project Explorer, choose Export File, and send the .bas file. The recipient can import it via File > Import File in the VBA editor. Note that macros may be blocked if the file is downloaded from the internet—they’ll need to unblock it in file properties.

Why does my macro work on my computer but not on my colleague’s?

This is usually due to security settings or missing references. Check that the other person has macros enabled (Trust Center settings). Also, if your macro uses features like ActiveX controls or specific libraries, those may not be available. To avoid issues, keep your code simple and avoid external references unless necessary.

Can I undo a macro after running it?

No, macros cannot be undone with Ctrl+Z. This is a fundamental limitation. To protect yourself, save a copy of your workbook before running any macro that modifies data. You can also add a line at the start of the macro to save a backup automatically, but it’s safer to do it manually.

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.