VBA course · Lesson 4 of 33

Your first macro: Sub, MsgBox, running it and a button

Write a macro from scratch: the Sub structure, MsgBox, comments and line continuation, then run it in five ways and assign it to a button on the sheet.

Beginner 14 min read

In The macro recorder: record, read and clean up code Excel wrote the code for you. Now you write your own from an empty module. By the end of this lesson you will have a macro that fills in an invoice header, you will know every way to run it, and you will have a button on the sheet that anyone can click.

The anatomy of a Sub

A macro is a Sub procedure, usually just called a Sub. Its skeleton never changes:

VBA
Sub SayHello()
    MsgBox "Hello, Excel!"
End Sub
The smallest possible macro
  • Sub starts the procedure. It is a keyword, so the editor colours it blue.
  • SayHello is the name you choose. Names must start with a letter, may contain letters, digits and underscores, cannot contain spaces or punctuation, and cannot be a VBA keyword such as Date or Sub. Up to 255 characters are allowed, but short descriptive names are best.
  • The brackets () are for parameters, values handed to the Sub when it is called. A macro you run from Excel has empty brackets. Parameters come in Functions and Subs: parameters, ByVal, ByRef and return values.
  • The lines inside are the body. Indent them with one Tab (four spaces) so the structure is easy to see.
  • End Sub closes the procedure.

Here is a tip that saves typing: in an empty module, type only sub SayHello and press Enter. The editor adds the brackets, the End Sub line and fixes the capitalisation for you.

Writing the macro step by step

Open a new workbook, save it as FirstMacro.xlsm, press Alt+F11 (Mac: Opt+F11), choose Insert > Module, and type the code below.

VBA
Option Explicit

Sub CreateInvoiceHeader()
    ' Builds a simple invoice header on the active sheet

    ' Company name and title
    Range("A1").Value = "Northwind Office Supplies"
    Range("A2").Value = "INVOICE"

    ' Labels
    Range("A4").Value = "Invoice no."
    Range("A5").Value = "Date"
    Range("A6").Value = "Customer"

    ' Values
    Range("B4").Value = "INV-2026-0147"
    Range("B5").Value = Date
    Range("B6").Value = "Contoso Ltd"

    ' A little formatting
    Range("A1").Font.Size = 16
    Range("A1:A2").Font.Bold = True
    Range("A4:A6").Font.Italic = True
    Columns("A:B").AutoFit

    MsgBox "Invoice header created.", vbInformation, "Done"
End Sub
Fill in the header of an invoice

Click inside the Sub and press F5. Switch back to Excel to admire the result.

AB
1Northwind Office Supplies
2INVOICE
3
4Invoice no.INV-2026-0147
5Date2026-12-02
6CustomerContoso Ltd

The sheet after CreateInvoiceHeader runs (B5 shows the current date)

What each part does

  • Option Explicit at the very top forces every variable to be declared. This macro uses no variables yet, but keep the line in every module (Variables and data types: Dim, Option Explicit and scope).
  • Range("A1").Value = "Northwind Office Supplies" puts text into a cell. Range("A1") is the cell, .Value is its content, and = here means "set to". Text always goes in double quotes.
  • Range("B5").Value = Date writes today's date. Date is a built-in VBA function, so it takes no quotes. Excel stores it as a real date that you can calculate with (Working with dates and times in VBA).
  • Font.Size, Font.Bold and Font.Italic change the look. You can set a property on a whole range at once, such as Range("A1:A2").
  • Columns("A:B").AutoFit resizes the columns to the content.
  • MsgBox shows a dialog. More on it below.

The code works on the active sheet, whichever sheet is in front when you run it. In Workbooks and worksheets in VBA you will learn to name the sheet explicitly so the macro always writes to the right place.

MsgBox: talking to the user

MsgBox is the simplest way for a macro to say something. Its full form has several arguments, but only the first is required:

VBA
Option Explicit

Sub MsgBoxExamples()
    ' Message only
    MsgBox "The report is ready."

    ' Message and an icon
    MsgBox "3 invoices are overdue.", vbExclamation

    ' Message, icon and a title for the dialog
    MsgBox "Backup saved to the Archive folder.", vbInformation, "Backup"

    ' Joining text and values with &
    MsgBox "You are working on sheet " & ActiveSheet.Name & "."
End Sub
MsgBox with one, two and three arguments

The second argument picks the icon and buttons (vbInformation, vbExclamation, vbCritical, vbQuestion), and the third sets the title bar text. The & operator glues pieces of text together, which lets you build messages from values. Talking to the user: MsgBox and InputBox shows how to ask Yes/No questions and react to the answer.

Note. When you call MsgBox as a statement, the arguments are written without brackets around them. MsgBox("Hi") also works with a single argument, but MsgBox("Hi", vbInformation) gives the compile error "Expected: =". The rule: use brackets only when you use the return value, for example answer = MsgBox("Continue?", vbYesNo).

Comments and long lines

Any text after an apostrophe is a comment and is shown in green. Use comments to explain why the code does something, not to repeat what it obviously does. You can put a comment on its own line or at the end of a code line:

VBA
Option Explicit

Sub WriteFooter()
    ' Payment terms agreed with all customers in 2026
    Range("A20").Value = "Payment due within 30 days."   ' printed on every invoice

    ' A long line split over three lines with " _"
    Range("A21").Value = "Please pay by bank transfer and quote " & _
        "the invoice number as the reference. " & _
        "Thank you for your business."
End Sub
Comments and a line continuation

A space followed by an underscore ( _) at the end of a line tells VBA "this statement continues on the next line". It is purely for readability. You cannot split a line inside a pair of quotes; close the text, add & _, and open new quotes on the next line, as above.

Tip. To comment out several lines at once, show the Edit toolbar (View > Toolbars > Edit) and use the Comment Block and Uncomment Block buttons. Handy when testing.

Five ways to run a macro

  1. From the editor: click inside the Sub and press F5 (Mac: Fn+F5), or click the green Run button on the toolbar.
  2. From the Macros dialog: in Excel press Alt+F8 (Mac: Opt+F8), choose the macro and click Run. The Options... button here lets you add or change a keyboard shortcut later.
  3. With a keyboard shortcut you assigned in the Options dialog, for example Ctrl+Shift+I (on a Mac, macro shortcuts use Opt+Cmd plus a letter).
  4. From a button or shape on the sheet (next section).
  5. From the Quick Access Toolbar or a custom ribbon group: File > Options > Quick Access Toolbar, choose Macros in the "Choose commands from" list, add your macro and pick an icon.

Only Subs without parameters that are not marked Private appear in the Macros dialog. That is a useful trick: helper procedures that should not be run directly can be declared Private Sub.

Assigning a macro to a button

Most people who use your workbook will never open the editor. Give them a button.

Using a shape (works everywhere, including Mac)

  1. Go to Insert > Shapes and draw a rounded rectangle on the sheet.
  2. Type a label into it, such as "Create invoice header", and format it as you like.
  3. Right-click the shape and choose Assign Macro....
  4. Pick CreateInvoiceHeader and click OK.
  5. Click a cell to deselect the shape, then click the shape. The macro runs.

To edit the shape later without running the macro, right-click it (or Ctrl+click).

Using a Form Control button (Windows and Mac)

  1. Click Developer > Insert and under Form Controls choose the first icon, Button.
  2. Drag a rectangle on the sheet. The Assign Macro dialog opens straight away.
  3. Choose the macro and click OK, then right-click the button and choose Edit Text to change its caption.
Watch out. The Developer > Insert menu also offers ActiveX Controls. They look similar but work differently, run their code in the sheet module, are Windows-only, and are known to misbehave with display scaling. For a simple "run this macro" button, always use a shape or a Form Control.

A second example: a reset button

A form that can be filled in usually needs a "clear" button as well. This macro empties the input cells but keeps the labels:

VBA
Option Explicit

Sub ClearInvoiceHeader()
    ' Clears only the values, keeps the labels in column A
    Range("B4:B6").ClearContents
    Range("B4").Select   ' put the cursor where the user types next
    MsgBox "Ready for a new invoice.", vbInformation
End Sub
Clear the variable parts of the invoice header

ClearContents removes values and formulas but keeps formatting; Clear would remove formatting too. Selecting B4 at the end is one of the few good reasons to use Select: it moves the user's cursor for their convenience. Assign this to a second shape labelled "Clear", and your sheet now has a tiny user interface.

Common mistakes

  • "Compile error: Expected: end of statement": often a missing & between text and a value, or a stray quote. Look for the red line.
  • "Sub or Function not defined": a typo in a command name, for example Msgbox written as MesBox. Because the editor capitalises known words, a word that stays lowercase is a hint.
  • The macro does not appear in Alt+F8: it is Private, it has parameters, it is in a sheet module of another workbook, or the workbook was saved as .xlsx and the code is gone.
  • Smart quotes: copying code from a word processor can turn " into curly quotes, which VBA does not understand. Type quotes in the editor.
  • The button runs the wrong macro after copying the sheet: the assignment points to a workbook and macro name. After copying sheets between files, right-click the button and assign it again.

Check yourself

1. Which line correctly ends a Sub procedure?

2. Which of these is a valid macro name?

3. What does the space-underscore " _" at the end of a line mean?

4. Why might a macro not appear in the Alt+F8 Macros list?

5. What is the recommended kind of button for running a simple macro on Windows and Mac?