VBA course · Lesson 5 of 33

Variables and data types: Dim, Option Explicit and scope

Store values in variables: Dim, the main VBA data types, Option Explicit, constants, object variables with Set, and procedure, module and public scope.

Beginner 16 min read

A variable is a named box in memory where your macro keeps a value while it runs: a customer's name, an invoice total, a row number, a sheet. Variables let a macro remember things, calculate with them and reuse them. They are the foundation of every macro beyond the simplest, so this lesson takes its time.

Declaring a variable with Dim

You create a variable with the Dim statement (short for dimension), giving it a name and a data type:

VBA
Option Explicit

Sub InvoiceTotal()
    Dim netAmount As Double
    Dim vatRate As Double
    Dim grossAmount As Double

    netAmount = 1250          ' price before tax
    vatRate = 0.2             ' 20% VAT
    grossAmount = netAmount * (1 + vatRate)

    MsgBox "Total including VAT: " & Format(grossAmount, "#,##0.00")
End Sub
Declare, assign, use

The message shows Total including VAT: 1,500.00. Three things happen with each variable:

  1. Declaration: Dim netAmount As Double reserves a box called netAmount that can hold a decimal number.
  2. Assignment: netAmount = 1250 puts a value into it. The = sign means "store the value on the right in the variable on the left".
  3. Use: netAmount * (1 + vatRate) reads the value back.

A variable keeps its value until you assign a new one or until the procedure ends. Then it disappears. Variables that have been declared but not assigned start with a default value: 0 for numbers, an empty string "" for text, False for Booleans.

Naming rules

Variable names follow the same rules as macro names: start with a letter, use only letters, digits and underscores, no spaces, no reserved words. VBA is not case sensitive, so Total and total are the same variable; the editor adjusts every occurrence to the capitalisation of the declaration. A popular style, used in this course, is camelCase: invoiceTotal, lastRow, customerName. Pick names that say what the value means, not what type it is.

The main data types

TypeHoldsExample valuesNotes
LongWhole numbers up to about plus or minus 2.1 billion42, -7, 1048576Use for counts and row numbers
IntegerWhole numbers from -32,768 to 32,767365Too small for row numbers; prefer Long
DoubleDecimal numbers, about 15 significant digits0.2, 1250.75Use for most calculations
CurrencyFixed 4 decimal places, very precise19.99Good for money sums without rounding drift
StringText"Contoso Ltd"Up to about 2 billion characters
BooleanTrue or FalseTrueFlags and yes/no answers
DateDate and time#2026-03-15#See the dates lesson
VariantAnything, including errors and arraysanyThe default when no type is given
Object / Range / WorksheetA reference to an Excel objecta cell, a sheetAssigned with Set

A few practical guidelines:

  • Use Long for anything you count, especially row numbers. Excel has 1,048,576 rows, far beyond Integer's 32,767 limit, and assigning a bigger number to an Integer stops the macro with "Overflow".
  • Use Double for amounts, rates and measurements. Use Currency when you add up many money values and need exact cents.
  • Use String for text, including codes that look like numbers but are not calculated with, such as postcodes "02139" or phone numbers. A Long would drop the leading zero.
  • Use Variant only when you need it: for values whose type you do not know in advance, such as a cell that may contain text or a number, or for arrays read from ranges (Arrays in VBA: static, dynamic and fast range processing).

Declaring several variables on one line

You can declare several variables in one Dim, but each needs its own As clause:

VBA
Dim firstName As String, lastName As String, age As Long
One line, several declarations
Watch out. Dim a, b, c As Long does not make three Long variables. Only c is Long; a and b become Variant because they have no type of their own. This is one of VBA's best-known traps.

Option Explicit: why it matters

Without Option Explicit, VBA silently creates a new Variant for any unknown name. That sounds convenient until you make a typo:

VBA
Sub CommissionWithoutExplicit()
    Dim commission As Double
    Dim sales As Double
    sales = 48000
    comission = sales * 0.05      ' typo: one m missing
    MsgBox "Commission: " & commission
End Sub
A bug that Option Explicit would catch

This macro runs without complaint and shows Commission: 0. The calculation went into a brand-new accidental variable called comission, while commission stayed 0. In a real workbook such a bug can go unnoticed for months. Put Option Explicit on the first line of the module and press F5 again: VBA refuses to run and highlights comission with "Variable not defined". The typo is found in a second.

Turn on Tools > Options > Require Variable Declaration so the line is added to every new module automatically (The Developer tab and the VBA editor). It only affects new modules; add the line by hand to existing ones.

Reading from and writing to cells

Most variables in Excel macros travel between cells and code. Here a macro reads a salary and a bonus percentage from a staff sheet, calculates, and writes the result back.

AB
1Annual salary52000
2Bonus %0.075
3Bonus

Before: input values in B1 and B2

VBA
Option Explicit

Sub CalculateBonus()
    Dim salary As Double
    Dim bonusPct As Double
    Dim bonus As Double

    ' Read from the sheet
    salary = Range("B1").Value
    bonusPct = Range("B2").Value

    ' Calculate in VBA
    bonus = Round(salary * bonusPct, 2)

    ' Write back to the sheet
    Range("B3").Value = bonus
End Sub
Read inputs, calculate, write the result
AB
1Annual salary52000
2Bonus %0.075
3Bonus3900

After: B3 holds 3900 (52,000 × 7.5%)

If B1 contained text such as "n/a", the line salary = Range("B1").Value would stop with "Type mismatch", because text cannot go into a Double. That is actually helpful: the error tells you the data is not what you expected. Error handling and debugging in VBA shows how to handle it gracefully.

Constants

When a value never changes while the macro runs, declare it as a constant with Const. Constants make code easier to read and change: if the VAT rate changes, you edit one line instead of hunting for 0.2 everywhere.

VBA
Option Explicit

Const VAT_RATE As Double = 0.2
Const COMPANY_NAME As String = "Northwind Office Supplies"

Sub ShowPriceWithVat()
    Dim net As Double
    net = 89.5
    MsgBox COMPANY_NAME & vbNewLine & _
        "Price incl. VAT: " & Format(net * (1 + VAT_RATE), "0.00")
End Sub
Constants at the top of a module

The message shows the company name and Price incl. VAT: 107.40. Writing constants in capitals is a common convention that makes them stand out. VBA also has many built-in constants, such as vbNewLine (a line break), vbYes, and xlUp.

Object variables and Set

Variables can also point to Excel objects: a range, a worksheet, a workbook. For objects you must use Set when assigning. Forgetting it is one of the most common beginner errors.

VBA
Option Explicit

Sub HighlightTotal()
    Dim ws As Worksheet
    Dim totalCell As Range

    Set ws = ActiveSheet
    Set totalCell = ws.Range("B3")

    totalCell.Font.Bold = True
    totalCell.Interior.Color = RGB(255, 242, 204)   ' light yellow
    MsgBox "Highlighted " & totalCell.Address & " on " & ws.Name
End Sub
Object variables need Set

After the Set lines, totalCell is just another name for cell B3 on that sheet. Anything you do to totalCell happens to the cell. Object variables make long code shorter and clearer, and they are faster than repeating Worksheets("Staff").Range("B3") again and again. You will use them in every lesson from Range and Cells: working with cells in VBA on.

Note. If you leave out Set and write totalCell = ws.Range("B3"), VBA tries to assign the cell's value to the object variable and stops with "Object variable or With block variable not set" (error 91). The rule: values use plain =, objects use Set ... =.

Scope: where a variable lives

Scope decides which parts of your code can see a variable, and lifetime decides how long it keeps its value.

DeclaredKeywordVisible inKeeps its value
Inside a SubDimThat procedure onlyUntil the procedure ends
Inside a SubStaticThat procedure onlyBetween calls, until the workbook closes or code is reset
Top of a moduleDim or PrivateEvery procedure in that moduleWhile the workbook is open
Top of a modulePublicEvery module in the projectWhile the workbook is open
VBA
Option Explicit

Private runCount As Long         ' module level: shared by all Subs below

Sub CountRuns()
    Static clicks As Long        ' remembers its value between calls
    Dim message As String        ' local: fresh each time

    clicks = clicks + 1
    runCount = runCount + 1
    message = "This macro has run " & clicks & " time(s)."
    MsgBox message
End Sub

Sub ShowModuleCount()
    MsgBox "Total runs in this module: " & runCount
End Sub
Procedure, Static and module-level variables

Run CountRuns three times and the message counts 1, 2, 3, because clicks is Static. ShowModuleCount can read runCount because it is declared at module level, but it cannot see clicks or message, which belong to CountRuns alone.

Prefer the narrowest scope that works. Local variables are easy to reason about; public variables can be changed by any code anywhere, which makes bugs hard to trace. If two Subs need to share a value, passing it as a parameter (Functions and Subs: parameters, ByVal, ByRef and return values) is usually cleaner than a public variable.

Tip. Module-level and Static values are wiped when you press the Reset button in the editor, when an unhandled error ends the code and you click End, or when you edit certain parts of the code. Do not rely on them to store important data for long; write it to a cell instead.

Variant and type conversion

When VBA moves a value between types it converts automatically where it can: Dim n As Long followed by n = "42" works, because the text "42" can become a number. n = "forty-two" fails with "Type mismatch". You can convert explicitly with functions such as CLng, CDbl, CStr and CDate, and check first with IsNumeric or IsDate:

VBA
Option Explicit

Sub ReadQuantity()
    Dim qty As Long
    If IsNumeric(Range("C2").Value) Then
        qty = CLng(Range("C2").Value)
        MsgBox "Quantity: " & qty
    Else
        MsgBox "C2 does not contain a number.", vbExclamation
    End If
End Sub
Checking a cell before converting it

The If ... Then ... Else structure is explained fully in Making decisions: If, ElseIf and Select Case.

Common mistakes

  • No Option Explicit: typos create silent new variables. Always use it.
  • Dim a, b As Long: only b is Long.
  • Integer for row numbers: Overflow above 32,767. Use Long.
  • Missing Set with objects: error 91.
  • Numbers stored as text in cells: reading them into a String keeps them as text, and "10" + "5" can give 105 instead of 15. Read numbers into numeric variables.
  • Reusing one variable for two meanings: a variable called temp that holds a name in one place and a total in another is a bug waiting to happen.

Check yourself

1. After Dim a, b As Long, what type is a?

2. Which type should you use for a row number?

3. Which statement correctly assigns a range to an object variable rng?

4. What does Option Explicit do?

5. A variable declared with Dim at the top of a module, outside any Sub, is visible in...