An example of a macro is a short VBA (Visual Basic for Applications) procedure that automates a repetitive task in Excel, such as the following code that formats the selected cells as bold with a yellow fill:
Sub FormatHighlight()
' Formats the currently selected cells
Selection.Font.Bold = True
Selection.Interior.Color = RGB(255, 255, 0) ' Yellow
End Sub
When you run this macro, it instantly applies bold text and a yellow background to whatever cells you have selected. Macros are essentially recorded or written sets of instructions that Excel executes on your behalf, saving you from performing the same manual steps over and over.
What Exactly Is a Macro?
A macro is a sequence of commands and functions that are stored in a VBA module within an Excel workbook. You can think of it as a mini-program that runs inside Excel. Macros can range from simple tasks like formatting cells to complex operations that manipulate data across multiple sheets, interact with other applications, or build custom functions.
There are two primary ways to create a macro:
- Record a macro: Excel records your mouse clicks and keystrokes as you perform an action, converting them into VBA code. This is great for beginners because you don’t need to know programming.
- Write VBA code manually: You open the Visual Basic Editor (VBE) and type the code yourself. This gives you full control and allows for logic like loops and conditionals.
Every macro must be stored in a module within a workbook, and the workbook must be saved as a macro-enabled file (with the .xlsm extension) to retain the macro.
How to Run a Macro
Once you have a macro, you can run it in several ways:
- Using the Macros dialog: Press
Alt+F8(orOption+F8on Mac), select the macro from the list, and click “Run”. - With a keyboard shortcut: When you record or create a macro, you can assign a shortcut key like
Ctrl+Shift+Hto trigger it. - From a button: Insert a shape or button on the worksheet and assign the macro to it, so clicking the button runs the macro.
- From the Developer tab: If the Developer tab is visible, click “Macros” to open the same dialog.
If the Developer tab isn’t visible, you can enable it via File > Options > Customize Ribbon and check “Developer”.
How to Create a Simple Macro by Recording
Recording is the fastest way to get a working macro without writing code. Here’s a step-by-step example that records a macro to apply a specific number format to selected cells:
- Select the cells you want to format (e.g., a range of numbers).
- Go to the Developer tab and click “Record Macro”.
- Give the macro a name (e.g.,
FormatAsCurrency) and optionally assign a shortcut key. - Perform the actions you want to record—for example, press
Ctrl+Shift+4to apply currency format, or go to Home > Number Format > Currency. - Click “Stop Recording” on the Developer tab.
Now, whenever you select different cells and run the macro, it will apply the same currency format. The recorded code will look something like:
Sub FormatAsCurrency()
Selection.NumberFormat = "$#,##0.00"
End Sub
Writing a Macro with Loops and Conditions
Manual recording is limited to linear actions. For more powerful macros, you’ll write code that can make decisions and repeat tasks. For example, the following macro loops through column A and highlights any cell that contains a value greater than 100:
Sub HighlightHighValues()
Dim cell As Range
For Each cell In Range("A1:A100")
If cell.Value > 100 Then
cell.Interior.Color = RGB(255, 0, 0) ' Red
End If
Next cell
End Sub
This macro uses a For Each loop and an If statement—two fundamental programming constructs that allow you to automate complex data processing tasks.
Common Problems and How to Avoid Them
Macros can sometimes cause issues, especially for beginners. Here are the most common pitfalls:
- Macro not running: If you get a “Macros are disabled” error, you need to enable macros in the Trust Center (File > Options > Trust Center > Macro Settings) or save the file as .xlsm.
- Wrong range selected: Many macros operate on the current selection. If you forget to select the correct cells before running, you may format the wrong data.
- Undoing a macro: Macros cannot be undone with
Ctrl+Z. Always save a backup copy of your workbook before running a macro that modifies data. - Code errors: A typo in VBA can cause a runtime error. Use the debugging tools in the VBE (like F8 to step through) to find the issue.
Frequently Asked Questions
Can I use a macro on a Mac?
Yes, Excel for Mac supports VBA macros. The Visual Basic Editor is available, and you can record and run macros. The keyboard shortcuts differ slightly (e.g., Option+F8 to open the Macros dialog), but the code syntax is identical.
Are macros safe?
Macros can contain malicious code, so only run macros from trusted sources. Excel displays a security warning when opening a file with macros; you can choose to enable them if you trust the file. Always scan downloaded workbooks with antivirus software.
How do I delete a macro?
Open the Visual Basic Editor (Alt+F11), find the module containing the macro in the Project Explorer, right-click the module and choose “Remove Module”, or simply delete the specific Sub procedure code.
What is the difference between a macro and a function?
A macro is a procedure that performs actions (like formatting or moving data), while a function in VBA (or a worksheet function) returns a value. You can call a macro from a button or shortcut, but you can’t call it directly from a cell formula. A custom VBA function can be used in a cell like =MyFunction(A1).
Can I share a macro with someone else?
Yes, you can share the workbook containing the macro. The recipient must enable macros when opening the file. Alternatively, you can export the module as a .bas file and import it into another workbook via the VBE.
Alternatives to Macros
If you find VBA intimidating, Excel offers other automation tools:
- Excel Tables and Formulas: Many repetitive tasks can be handled with dynamic formulas like
SUMIFSorXLOOKUPwithout any programming. - Conditional Formatting: Instead of a macro to highlight cells, use built-in rules (Home > Conditional Formatting) to automatically format based on values.
- Power Query: For data cleaning and transformation, Power Query (Get & Transform Data) provides a no-code interface to automate import and reshaping of data.
- Office Scripts: In Excel for the web and Microsoft 365, you can use Office Scripts (TypeScript) to automate tasks, though they are not compatible with VBA.
Choosing the right tool depends on your needs: for simple formatting, conditional formatting might suffice; for complex data processing, Power Query is often more efficient than VBA.
Related
- Selected Cell How Many Values? Excel Count Explained
- What Is the Shortcut for Copying? (Ctrl+C, Cmd+C)
- Data Entry for Students: Real Work & Pay
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- Excel Macro Recorder: Is It Available Without a License?Excel’s Macro Recorder is built into the desktop app; it is not a separate add-on that needs its…
- VBA Active Worksheet: How to Reference the Current SheetIn Excel VBA, use ActiveSheet to refer to the sheet that is currently active in the Excel window.…
- Excel VBA Link to Worksheet: Methods and ExamplesIn Excel VBA, link to a worksheet by referring to it with ThisWorkbook.Worksheets("SheetName"); to create a clickable link…
- Excel VBA Data Validation Drop-Down Lists: How to Build ThemTo create an Excel data-validation drop-down list with VBA, apply the xlValidateList validation type to the target cells…
- VBA MsgBox Multiple Lines: Line Breaks and ExamplesTo show multiple lines in a VBA MsgBox, join the text with the built-in line-break constant vbCrLf. For…
- Unload UserForm VBA: Close Forms and Reset State SafelyIn VBA, use Unload UserForm1 to close and unload a form, or use Unload Me from code inside…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.