Skip to content

Lesson 30 of 92 · Free Excel Course

Excel

Excel Macros and VBA for Beginners: Record a Macro and Write a VBA Function

Record your first Excel macro, run it, save as .xlsm, read the VBA code and write a custom VBA function like =AddTax(B2,0.08). Free practice file.

If you do the same clicks every week, such as bolding a header, shading it and widening the columns, Excel can learn those steps and repeat them in a split second. That saved set of steps is a macro. Behind every macro is a little program written in VBA, and once you can read a few lines of it you can also write your own worksheet functions. This lesson takes you from zero to a recorded macro, a hand-written one, and a custom function, =AddTax(B2,0.08), that works just like SUM. You need the desktop app for Windows or Mac; we'll cover the web at the end.

What is a macro, and what is VBA?

A macro is a recording of actions you can play back. VBA (Visual Basic for Applications) is the language Excel saves those actions in. You don't need to know VBA to record a macro: Excel writes the code for you while you click. VBA becomes useful when you want to tidy up a recording or build something the recorder can't, like a function.

Two kinds of VBA code matter for beginners:

  • A Sub (short for subroutine) does something: formats cells, types a date, shows a message.
  • A Function works out a value and returns it to a cell, so you can use it in a formula.

One warning before you start: macros can't be undone. Ctrl+Z won't reverse what a macro did, so save your workbook first or practise on a copy.

Show the Developer tab

All the macro buttons live on the Developer tab, which Excel hides by default.

  1. Click File, then Options.
  2. Choose Customize Ribbon.
  3. In the Main Tabs list on the right, tick Developer and click OK.

The Developer tab now sits next to View and stays there. Its Code group holds Visual Basic, Macros, Record Macro, Use Relative References and Macro Security.

On a Mac, go to Excel, Preferences, Ribbon & Toolbar, tick Developer under Main Tabs, and click Save.

Macro security: Enable Content and blocked downloads

Macros are real programs, and criminals have long hidden harmful ones in email attachments. That's why Excel is careful with them.

The yellow bar. When you open a file with macros, Excel normally disables them and shows a yellow SECURITY WARNING bar saying macros have been disabled, with an Enable Content button. Click it only if you know where the file came from. Excel then remembers the file as a trusted document.

The red bar. Since 2022, Excel on Windows goes further for files from the internet. Windows tags downloads and email attachments with a hidden label called the Mark of the Web, and Excel blocks every macro in those files. You'll see a red SECURITY RISK bar saying Microsoft has blocked macros because the source is untrusted, and there's no Enable Content button. If you truly trust the file:

  1. Close it in Excel.
  2. In File Explorer, right-click the file and choose Properties.
  3. On the General tab, tick Unblock near the bottom, then click OK.
  4. Open the file again.

Trust Center settings. To see your setting, click File, Options, Trust Center, Trust Center Settings, then Macro Settings (or click Macro Security on the Developer tab). The default, Disable VBA macros with notification, is the right choice for almost everyone. Avoid Enable VBA macros; Microsoft labels it "not recommended" because any file could run code.

The internet-file block applies to Office on Windows; Microsoft says it doesn't affect Excel for Mac or the web.

Record your first macro

We'll record a macro that formats a header row. Here's the sheet before:

A1Item
ABC
1ItemPriceWith tax
2Desk lamp$24.00
3Office chair$129.00
4Notebook pack$8.50
5Monitor$189.99
6Keyboard$45.00
7USB cable$6.25
Your taskPracticeVBA codeAnswer key
Before: a plain header in A1:C1 on the practice sheet.
  1. Click cell A1.
  2. On the Developer tab, click Record Macro. The Record Macro box opens.
  3. Macro name: type FormatHeader. The name must start with a letter and can use letters, numbers and underscores, but no spaces.
  4. Shortcut key: click the box and type a capital H (hold Shift). Your shortcut becomes Ctrl+Shift+H. A lowercase letter would give Ctrl+H, which would replace Excel's own Find and Replace shortcut while this workbook is open.
  5. Store macro in: leave This Workbook. Choose Personal Macro Workbook instead if you want the macro in every file you open; Excel keeps those in a hidden file called PERSONAL.XLSB.
  6. Type a short Description if you like, then click OK. Recording has started.
  7. Select A1:C1, press Ctrl+B for bold, and pick a light blue from Fill Color on the Home tab.
  8. Select columns A to C and double-click a column border to AutoFit them.
  9. Back on the Developer tab, click Stop Recording.

The recorder captures almost everything, mistakes included. If you slip, stop and record again.

Relative or absolute? By default the recorder saves exact addresses, so this macro will always format A1:C1. If you turn on Use Relative References (Developer tab) before recording, the steps are saved relative to the active cell instead, so the macro works wherever you start it. For a header that's always in row 1, leave it off.

Run a macro: Alt+F8, a shortcut or a button

Clear the formatting from A1:C1 (Home, Clear, Clear Formats), then try any of these:

  • The Macros box: press Alt+F8 (or click Macros on the Developer tab), pick FormatHeader, and click Run.
  • The shortcut: press Ctrl+Shift+H.
  • A button: on the Developer tab, click Insert, then Button under Form Controls. Drag a rectangle on the sheet; the Assign Macro box opens. Choose FormatHeader and click OK. Right-click the button to rename it. You can also right-click any shape and choose Assign Macro.
A1Item
ABC
1ItemPriceWith tax
2Desk lamp$24.00
3Office chair$129.00
4Notebook pack$8.50
5Monitor$189.99
6Keyboard$45.00
7USB cable$6.25
After FormatHeader runs: A1:C1 is bold and shaded, and the columns are wide enough for the text.

On a Mac, macro shortcuts use Option+Cmd+letter (Ctrl+letter also works), and Ctrl+Shift+letter for a capital.

Save as a macro-enabled workbook (.xlsm)

A normal .xlsx file can't hold macros. Press F12 (or File, Save As), and under Save as type choose Excel Macro-Enabled Workbook (*.xlsm).

If you just press Ctrl+S on an .xlsx file, Excel warns that "the following features cannot be saved in macro-free workbooks: VB project". Click No, then pick the .xlsm type. Clicking Yes saves the file without your code, and the macros are gone once you close it.

Open the VBA editor and read the recorded code

Press Alt+F11 to open the Visual Basic Editor (or click Visual Basic on the Developer tab). On the left, the Project pane lists your workbook; your recording is in Modules, Module1. Double-click it. You'll see something like this (your colour numbers will differ):

Sub FormatHeader()
'
' FormatHeader Macro
' Keyboard Shortcut: Ctrl+Shift+H
'
    Range("A1:C1").Select
    Selection.Font.Bold = True
    With Selection.Interior
        .Pattern = xlSolid
        .ThemeColor = xlThemeColorAccent1
        .TintAndShade = 0.799981688894314
    End With
    Columns("A:C").EntireColumn.AutoFit
End Sub

Reading it line by line:

  • Sub FormatHeader() starts the macro and End Sub ends it.
  • Lines starting with an apostrophe are comments: notes that VBA ignores.
  • Range("A1:C1").Select selects the header cells, and Selection.Font.Bold = True makes them bold.
  • The With ... End With block sets the fill colour. Every line starting with a dot belongs to Selection.Interior.
  • Columns("A:C").EntireColumn.AutoFit widens the columns.

On a Mac, click Visual Basic on the Developer tab or choose Tools, Macro, Visual Basic Editor. Microsoft lists Fn+Option+F11 as the shortcut.

Write your first Sub by hand

In the editor, click Insert, then Module to get a blank page. Type this:

Sub StampDate()
    ActiveCell.Value = Date
    ActiveCell.NumberFormat = "mm/dd/yyyy"
    MsgBox "Today's date is in " & ActiveCell.Address
End Sub
  • ActiveCell.Value = Date puts today's date in whichever cell is selected. Date is a built-in VBA function.
  • ActiveCell.NumberFormat = "mm/dd/yyyy" displays it as a date, like 11/22/2026.
  • MsgBox pops up a message with an OK button. The & joins the text to the cell's address, so you'll see "Today's date is in $E$1".

Go back to Excel, click E1, press Alt+F8, and run StampDate. Unlike the TODAY() formula from Dates and times, this date is a fixed value: it won't change tomorrow.

Write a custom function: AddTax

This is where "VBA Excel function" gets interesting. In the same module, below End Sub, type:

Function AddTax(amount, rate)
    AddTax = amount * (1 + rate)
End Function
  • Function AddTax(amount, rate) names the function and its two inputs, called arguments.
  • AddTax = amount * (1 + rate) does the maths. Giving the answer to the function's own name is how VBA sends the result back to the cell.
  • End Function closes it.

Now in Excel, click C2, type =AddTax(B2,0.08), press Enter, and fill down to C7:

C2=AddTax(B2,0.08)
ABC
1ItemPriceWith tax
2Desk lamp$24.00$25.92
3Office chair$129.00$139.32
4Notebook pack$8.50$9.18
5Monitor$189.99$205.19
6Keyboard$45.00$48.60
7USB cable$6.25$6.75
AddTax adds 8% to each price: 24 × 1.08 = 25.92, and 189.99 × 1.08 = 205.1892, shown as $205.19.

It behaves like a built-in function: it recalculates when a price changes, you can point the rate at a cell such as =AddTax(B2,$F$1) (see absolute references), and it appears under User Defined in the Insert Function box. Of course =B2*(1+0.08) gives the same answer; the point is that a named function is easier to read and reuse, and you can build far more complex rules into one.

Microsoft's rule: a function can only return a value. If you try to make it change fonts, colours or other cells, the cell shows #VALUE!. Use a Sub for that.

Sub vs Function at a glance

SubFunction
What it doesPerforms actionsReturns a value
How you use itAlt+F8, a shortcut or a buttonIn a formula, like a built-in function
Can format cellsYesNo (gives #VALUE!)
Can the recorder make itYesNo, you type it
ExampleFormatHeader, StampDateAddTax

Excel for the web and Mac

Excel for the web can't create, run or edit VBA macros. You can still open and edit an .xlsm file; the code stays inside, and Open in Desktop App lets you use it. The web's own automation is Office Scripts: on the Automate tab, Record Actions records steps as a script written in TypeScript, not VBA. Office Scripts also work in Excel for Windows and Mac, but only on Microsoft 365 plans that include them.

Excel for Mac runs VBA. The differences are the menu paths above, the Option+Cmd shortcut keys, and no ActiveX controls, so use Form Control buttons.

Try it yourself

Download the practice workbook. It's a normal .xlsx with no macros inside, so it opens without any security warning. The code you need is on the VBA code sheet as plain text, one line per row, ready to copy.

  1. Show the Developer tab.
  2. On the Practice sheet, record FormatHeader with the shortcut Ctrl+Shift+H, formatting A1:C1.
  3. Clear the formatting, then run the macro with Alt+F8 and again with the shortcut. Add a button for it.
  4. Save the file as macros-and-vba-practice.xlsm.
  5. Press Alt+F11, insert a module, and paste in StampDate and AddTax from the VBA code sheet.
  6. In C2, type =AddTax(B2,0.08) and fill down to C7. In C8, total the column with SUM.
  7. Click E1 and run StampDate.

Compare with the Answer key sheet: C2:C7 should match, and C8 should be $434.96.

Common mistakes

  • "Macros have been disabled" or the red SECURITY RISK bar. Click Enable Content for a file you trust, or unblock a downloaded file in its Properties.
  • Saving as .xlsx. Clicking Yes in the macro-free warning deletes your code. Always save as .xlsm.
  • #NAME? in a cell. The function's name is misspelt, macros are off, or the code is in another workbook that's closed. For a function in PERSONAL.XLSB, write =PERSONAL.XLSB!AddTax(B2,0.08).
  • Compile error. A red line in the editor means VBA can't read your code, often a missing quote, bracket or End Sub. Fix the red line and run again.
  • Spaces in macro names. Format Header won't be accepted; use FormatHeader or Format_Header.
  • Overwriting a shortcut. Ctrl plus a lowercase letter can replace Excel's own shortcut (Ctrl+C!). Use Ctrl+Shift plus a capital.
  • Expecting Undo to work. It won't after a macro. Save first.

What's next

You've recorded a macro, read its code, written a Sub and built your own worksheet function: the core of VBA. Go back to Keyboard shortcuts (and grab the printable shortcuts cheat sheet), or return to the full Excel course. The next lesson, Power Query and Power Pivot, automates importing and cleaning data without any code.

Frequently asked questions

What's the difference between a macro and VBA?

A macro is a saved set of steps that Excel can repeat for you. VBA (Visual Basic for Applications) is the programming language those steps are stored in. When you record a macro, Excel writes the VBA for you; you can also type VBA yourself in the Visual Basic Editor (Alt+F11).

Why are macros blocked or disabled in my Excel file?

Excel disables macros by default and shows a yellow SECURITY WARNING bar with an Enable Content button. If the file came from the internet or an email, Excel on Windows blocks macros completely and shows a red SECURITY RISK bar. Only if you trust the file, close it, right-click it in File Explorer, choose Properties, tick Unblock on the General tab, and click OK.

What is the difference between a Sub and a Function in VBA?

A Sub does things: it formats cells, types values or shows messages, and you run it from the Macros box, a shortcut or a button. A Function works out a value and hands it back to a cell, so you use it in a formula like =AddTax(B2,0.08). A function can't change formatting or other cells.

Why does my custom VBA function show #NAME?

Excel can't find the function. The usual causes are a typo in the name, macros being disabled, the code being saved in a different workbook that isn't open, or the file having been saved as .xlsx, which strips the code. If the function lives in your Personal Macro Workbook, write =PERSONAL.XLSB!AddTax(B2,0.08).

Can I run macros in Excel for the web?

No. Microsoft says you can't create, run or edit VBA macros in Excel for the web, though you can open and edit a workbook that contains them, and the code stays in the file. Click Open in Desktop App to use them. The web alternative is Office Scripts on the Automate tab, if your Microsoft 365 plan includes it.

Can I undo a macro?

No. Microsoft warns that macros can't be undone with Ctrl+Z. Save your workbook before you run a new macro, or test it on a copy.