
π This article includes 1 downloadable practice file β
Every macro you will ever write stores things for a moment: a row number, a customer name, a running total, today’s date. Those little storage boxes are variables. Get them right at the start and most of the strange errors beginners hit simply never happen. This first lesson sets up the editor, writes a real macro, and explains variables properly.
In this article
Open the VBA editor
- Show the Developer tab: File βΊ Options βΊ Customize Ribbon, tick Developer.
- Press Alt+F11 to open the Visual Basic Editor.
- Insert βΊ Module. The white area on the right is where code goes.
- Save your workbook as .xlsm or .xlsb β a plain .xlsx throws the code away when it closes.
Option Explicit, which catches typos before they become bugs.Your first macro
Option Explicit
Sub HelloTotal()
Dim total As Double
total = Application.WorksheetFunction.Sum(Range("B2:B10"))
MsgBox "The total is " & Format(total, "#,##0.00")
End Sub
Put the cursor anywhere inside it and press F5. Three ideas are already here: a variable (total), a data type (Double), and joining text with &.
Declaring variables with Dim
Dim means βmake a box with this name and this typeβ. You can declare several on one line, but each needs its own type:
Dim r As Long, lastRow As Long ' both Long
Dim a, b As Long ' careful: a is Variant, only b is Long
That second line catches almost everyone once. Write the type after every name.
The data types you will actually use
| Type | Holds | Use for |
|---|---|---|
Long |
Whole numbers up to about Β±2.1 billion | Row numbers, counters, quantities |
Double |
Decimal numbers | Amounts, rates, percentages |
Currency |
Exact money values (4 decimals) | Totals where paise must not drift |
String |
Text | Names, codes, file paths |
Date |
Date and time | Invoice dates, deadlines |
Boolean |
True / False | Flags such as βfoundβ |
Variant |
Anything | Ranges read into arrays, values of unknown type |
Range, Worksheet |
Objects | Cells and sheets (need Set) |
Integer for row numbers. It stops at 32,767, and sheets have over a million rows β you get βOverflowβ (error 6) the first time data grows. Use Long; it is no slower.Objects need Set
Dim ws As Worksheet, cell As Range
Set ws = ThisWorkbook.Worksheets("Sales")
Set cell = ws.Range("E2")
cell.Value = cell.Value * 1.18
Plain values (numbers, text, dates) are assigned with =. Objects (sheets, ranges, workbooks) need Set. Forgetting Set gives βObject variable or With block variable not setβ (error 91).
Variable scope: where a variable lives
- Inside a Sub (
Diminside): exists only while that Sub runs. Use this 95% of the time. - Top of a module (
Private x As Longabove all Subs): shared by every Sub in that module. - Public (
Public x As Longat the top of a module): visible everywhere. Use sparingly β values hang around and cause surprises.
Const is a variable that never changes. Put fixed values like GST rates at the top so you only change them in one place:
Const GST_RATE As Double = 0.18
Const SHEET_NAME As String = "Sales"
Reading and writing cells with variables
Sub AddGST()
Dim ws As Worksheet, r As Long, lastRow As Long
Dim amount As Double
Set ws = ThisWorkbook.Worksheets("Sales")
lastRow = ws.Cells(ws.Rows.Count, "B").End(xlUp).Row
For r = 2 To lastRow
amount = ws.Cells(r, "B").Value
ws.Cells(r, "C").Value = Round(amount * (1 + GST_RATE), 2)
Next r
End Sub
Don’t worry about the loop yet β that’s lesson 6. Notice how each variable has one clear job.
Where people go wrong
| Error | Why | Fix |
|---|---|---|
| Type mismatch (13) | Putting text like βN/Aβ into a Long or Double | Check with IsNumeric() first |
| Overflow (6) | Integer used for rows or big numbers | Use Long or Double |
| Variable not defined | Typo, caught by Option Explicit | Good β fix the spelling |
| Object variable not set (91) | Missing Set for a Range/Worksheet |
Add Set |
| Dates become numbers like 45567 | Date written into a cell formatted as General | Format the column as a date |
Practice
The practice workbook has a Sales sheet and buttons for the macros above, plus three broken macros β one per common error β to fix yourself. Press F8 to step through line by line and watch variables in the Locals window (View βΊ Locals Window).
Next: ranges β Cells, Offset, Resize and finding the last row properly.
Test formulas dynamically in our web formula laboratory or download the companion Excel workbook.
π Practice files for this article
- πPractice workbook with all course macros (.xlsm)Open it, click Enable Content in the yellow bar, go to the Macros sheet and press any button. 60 sales rows included to test on.β¬ XLSM Β· 29 KB
Free to use for learning. Files with macros (.bas) are plain text β import them with Alt+F11 β File β Import File, and always test on a copy.
Atul (AJ) builds office-automation and local-first AI tools as Atulya AI, and works with Excel, SAP and Oracle EPM every day. He writes about the shortcuts, macros and automations that actually save time β plus the occasional wacky fact. Videos on YouTube: Lazy Automator AI (@LazyAutomatorAI).
More posts by Atul βStuck on a step? Ask a question and the AI answers using this article.