VBA Guide

Excel VBA Macros: Your First Sub, Explained

A macro is just a saved sequence of steps Excel can run for you — the same thing you'd do by hand, minus the hand. Here's how a basic macro is structured, and the three things you'll use constantly.

Sub procedures: where macro code lives

Every macro is written inside a Sub block — the VBA equivalent of a named block of instructions:

Sub Greet() MsgBox "Hello" End Sub

Sub Greet() starts the procedure and names it "Greet"; End Sub marks where it ends. Everything between the two lines runs when the macro is called.

MsgBox: a simple popup

MsgBox shows a small popup dialog with whatever text you give it — the easiest way to confirm a macro ran, or to show a quick message to whoever's using the spreadsheet.

For loops: repeating an action

VBA's For loop runs a block a fixed number of times, using a counter variable:

For i = 1 To 10 Debug.Print i Next i

Debug.Print writes to the Immediate window (VBA's console) instead of a popup — the standard way to check what a macro is doing while you're writing it. This loop counts from 1 to 10, printing each number.

Referencing cells: Range and Cells

To read or write a cell's value from a macro, use Range (with an A1-style reference) or Cells (with row/column numbers):

Sheet1.Range("A1").Value = "Done" Sheet1.Cells(1, 1).Value = "Done" ' same cell, different syntax

Prefixing with the sheet name (Sheet1.) makes the macro explicit about which sheet it's touching — leaving it off defaults to whichever sheet happens to be active, which is a common source of macros that "work on my machine" but write to the wrong tab elsewhere.

Common mistake: forgetting Next i (or the matching End Sub) — VBA's block structure requires explicit closing statements, unlike Python's indentation-based blocks. A missing one usually shows up as a compile error before the macro even runs.

Try it yourself

Practice writing real VBA macros with instant feedback.

Start practicing VBA →