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.
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:
Sub SayHello()
MsgBox "Hello, Excel!"
End SubSubstarts the procedure. It is a keyword, so the editor colours it blue.SayHellois 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 asDateorSub. 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 Subcloses 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.
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 SubClick inside the Sub and press F5. Switch back to Excel to admire the result.
| A | B | |
|---|---|---|
| 1 | Northwind Office Supplies | |
| 2 | INVOICE | |
| 3 | ||
| 4 | Invoice no. | INV-2026-0147 |
| 5 | Date | 2026-12-02 |
| 6 | Customer | Contoso Ltd |
The sheet after CreateInvoiceHeader runs (B5 shows the current date)
What each part does
Option Explicitat 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,.Valueis its content, and=here means "set to". Text always goes in double quotes.Range("B5").Value = Datewrites today's date.Dateis 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.BoldandFont.Italicchange the look. You can set a property on a whole range at once, such asRange("A1:A2").Columns("A:B").AutoFitresizes the columns to the content.MsgBoxshows 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:
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 SubThe 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.
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:
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 SubA 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.
Five ways to run a macro
- From the editor: click inside the Sub and press F5 (Mac: Fn+F5), or click the green Run button on the toolbar.
- 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.
- 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).
- From a button or shape on the sheet (next section).
- 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)
- Go to Insert > Shapes and draw a rounded rectangle on the sheet.
- Type a label into it, such as "Create invoice header", and format it as you like.
- Right-click the shape and choose Assign Macro....
- Pick
CreateInvoiceHeaderand click OK. - 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)
- Click Developer > Insert and under Form Controls choose the first icon, Button.
- Drag a rectangle on the sheet. The Assign Macro dialog opens straight away.
- Choose the macro and click OK, then right-click the button and choose Edit Text to change its caption.
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:
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 SubClearContents 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
Msgboxwritten asMesBox. 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?
Every Sub is closed with End Sub. Exit Sub leaves early, but the procedure still needs End Sub at the bottom.
2. Which of these is a valid macro name?
Names must start with a letter and cannot contain spaces. Underscores and digits are fine after the first letter.
3. What does the space-underscore " _" at the end of a line mean?
It is the line-continuation character, used to split long statements for readability.
4. Why might a macro not appear in the Alt+F8 Macros list?
The dialog lists only public Subs without parameters. Private and parameterised procedures are hidden.
5. What is the recommended kind of button for running a simple macro on Windows and Mac?
Shapes and Form Controls work on both platforms and simply run the assigned macro.