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.
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:
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 SubThe message shows Total including VAT: 1,500.00. Three things happen with each variable:
- Declaration:
Dim netAmount As Doublereserves a box callednetAmountthat can hold a decimal number. - Assignment:
netAmount = 1250puts a value into it. The=sign means "store the value on the right in the variable on the left". - 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
| Type | Holds | Example values | Notes |
|---|---|---|---|
| Long | Whole numbers up to about plus or minus 2.1 billion | 42, -7, 1048576 | Use for counts and row numbers |
| Integer | Whole numbers from -32,768 to 32,767 | 365 | Too small for row numbers; prefer Long |
| Double | Decimal numbers, about 15 significant digits | 0.2, 1250.75 | Use for most calculations |
| Currency | Fixed 4 decimal places, very precise | 19.99 | Good for money sums without rounding drift |
| String | Text | "Contoso Ltd" | Up to about 2 billion characters |
| Boolean | True or False | True | Flags and yes/no answers |
| Date | Date and time | #2026-03-15# | See the dates lesson |
| Variant | Anything, including errors and arrays | any | The default when no type is given |
| Object / Range / Worksheet | A reference to an Excel object | a cell, a sheet | Assigned 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:
Dim firstName As String, lastName As String, age As LongDim 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:
Sub CommissionWithoutExplicit()
Dim commission As Double
Dim sales As Double
sales = 48000
comission = sales * 0.05 ' typo: one m missing
MsgBox "Commission: " & commission
End SubThis 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.
| A | B | |
|---|---|---|
| 1 | Annual salary | 52000 |
| 2 | Bonus % | 0.075 |
| 3 | Bonus |
Before: input values in B1 and B2
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| A | B | |
|---|---|---|
| 1 | Annual salary | 52000 |
| 2 | Bonus % | 0.075 |
| 3 | Bonus | 3900 |
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.
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 SubThe 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.
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 SubAfter 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.
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.
| Declared | Keyword | Visible in | Keeps its value |
|---|---|---|---|
| Inside a Sub | Dim | That procedure only | Until the procedure ends |
| Inside a Sub | Static | That procedure only | Between calls, until the workbook closes or code is reset |
| Top of a module | Dim or Private | Every procedure in that module | While the workbook is open |
| Top of a module | Public | Every module in the project | While the workbook is open |
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 SubRun 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.
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:
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 SubThe 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: onlybis Long.- Integer for row numbers: Overflow above 32,767. Use Long.
- Missing
Setwith objects: error 91. - Numbers stored as text in cells: reading them into a String keeps them as text, and
"10" + "5"can give105instead of 15. Read numbers into numeric variables. - Reusing one variable for two meanings: a variable called
tempthat 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?
Each variable needs its own As clause. Without one, a is a Variant.
2. Which type should you use for a row number?
Rows go up to 1,048,576, far above Integer's limit of 32,767.
3. Which statement correctly assigns a range to an object variable rng?
Object variables are assigned with Set. Without it you get error 91.
4. What does Option Explicit do?
It turns typos in variable names into compile errors instead of silent bugs.
5. A variable declared with Dim at the top of a module, outside any Sub, is visible in...
Module-level Dim or Private variables are shared by all procedures in the same module. Public makes them visible to other modules.