Excel VBA Variables and Data Types: A Practical Guide

Excel VBA Variables and Data Types: A Practical Guide

πŸ“Ž This article includes 1 downloadable practice file ↓

⏱ 5 min read

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
  1. Open the VBA editor
  2. Your first macro
  3. Declaring variables with Dim
  4. The data types you will actually use
  5. Objects need Set
  6. Variable scope: where a variable lives
  7. Reading and writing cells with variables
  8. Where people go wrong
  9. Practice
  10. Continue learning

Open the VBA editor

  1. Show the Developer tab: File β€Ί Options β€Ί Customize Ribbon, tick Developer.
  2. Press Alt+F11 to open the Visual Basic Editor.
  3. Insert β€Ί Module. The white area on the right is where code goes.
  4. Save your workbook as .xlsm or .xlsb β€” a plain .xlsx throws the code away when it closes.
πŸ’‘ In the editor, turn on Tools β€Ί Options β€Ί Require Variable Declaration. From then on every new module starts with 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 &.

Advertisement

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)
⚠️ Don’t use 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 (Dim inside): exists only while that Sub runs. Use this 95% of the time.
  • Top of a module (Private x As Long above all Subs): shared by every Sub in that module.
  • Public (Public x As Long at 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.

⚑ Interactive Practice Lab & Formula Tester:

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.

✨ Ask AI about this article

Stuck on a step? Ask a question and the AI answers using this article.

Free Β· AI can be wrong

Leave a Reply

Your email address will not be published. Required fields are marked *