Curious Minds

Clear answers to science and history questions

VBA Declare Variable: Types, Examples, and Scope

· 7 min read · Science

To declare a variable in VBA, use a declaration statement such as Dim count As Long. The statement gives the variable a name and, with As, a data type; place it inside a procedure for a local variable or at the top of a module for a wider scope.

What a VBA variable declaration does

A variable is a named place for a value that a macro can read or change while it runs. Declaring it tells VBA that the name is valid and, when a type is specified, what kind of value it is intended to hold. Declarations also make code easier to understand: rowNumber declared as Long communicates more than a loosely named value whose purpose and type are unclear.

The most common declaration keyword is Dim. For example, inside a procedure:

Sub ShowTotal()
    Dim total As Double
    total = 12.5 + 7.25
    MsgBox total
End Sub

Here, total exists while ShowTotal runs. Its type, Double, is suitable for many decimal calculations. Declaring a variable does not necessarily assign the final value you want; code usually sets or updates that value separately.

How to declare a variable in the VBA editor

In Excel for Microsoft 365 on Windows, press Alt+F11 to open the Visual Basic Editor, select or insert a module, and write declarations in a procedure or in the module’s declarations area. On a Mac, use Tools > Macro > Visual Basic Editor if that menu is available, or the Visual Basic Editor command on the Developer tab; keyboard shortcuts can differ by keyboard and Excel settings.

  1. Choose a clear variable name, such as lastRow or invoiceDate.
  2. Choose an appropriate type, such as Long, String, or Date.
  3. Write Dim variableName As DataType.
  4. Assign a value before relying on it, and run the macro to check the result.

A simple Excel example, with a worksheet row number stored in a variable, looks like this:

Sub ReportLastRow()
    Dim lastRow As Long
    lastRow = Cells(Rows.Count, 1).End(xlUp).Row
    MsgBox lastRow
End Sub

This finds the last used cell in column A on the active sheet. In larger macros, qualifying Cells and Rows with a specific worksheet is safer than depending on whichever sheet is active.

Choosing a VBA data type

Use a type that matches the values and operations your code needs. Common choices include:

  • Long: whole numbers, including row and column indexes. It supports a much larger range than the older Integer type, so it is generally the better default for counts and Excel row numbers.
  • Double: numbers that may include decimal fractions, such as measurements or calculated values.
  • String: text, such as a customer name or a worksheet name.
  • Boolean: either True or False, often used for conditions and status flags.
  • Date: dates and times.
  • Variant: a flexible type that can hold different kinds of values. It can be useful when values are genuinely mixed, but a specific type makes intent clearer and can help catch mistakes.
  • Object or a specific object type, such as Worksheet: references to Excel objects rather than ordinary text or numbers.

For example, when a variable will hold a worksheet reference, use an object assignment with Set:

Sub ReadSheetName()
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Worksheets("Data")
    MsgBox ws.Name
End Sub

Set is used to assign object references. It is not used for ordinary values such as numbers or strings. Also note that VBA’s Integer is a 16-bit whole-number type; Excel workbooks can have far more rows than its upper limit, which is why Long is appropriate for row indexes.

Multiple variables, initialization, and Option Explicit

You can declare several variables in one statement, but write the type after each name. In Dim first, second As Long, only second is a Long; first is a Variant. This common VBA quirk can be avoided by making each type explicit:

Dim first As Long, second As Long
Dim productName As String, isAvailable As Boolean

VBA gives a newly declared variable a default initial value: numeric types start at zero, strings at an empty string, Booleans at False, and object references at Nothing. Still, assigning an intentional starting value can make logic easier to follow. An object reference must be assigned before you use its properties or methods.

Put Option Explicit at the very top of a module, before procedures, to require variables to be declared. In the Visual Basic Editor, Tools > Options > Editor includes a “Require Variable Declaration” setting that inserts this directive in new modules. Existing modules may need the line added manually. With it enabled, a misspelled variable name becomes a compile error instead of silently creating an unintended variable.

Scope and lifetime: where a variable is available

A declaration’s location affects where the variable can be used and how long its value lasts. The main options are:

  • Procedure-level: Declare with Dim inside a Sub or Function. The variable is available only there and normally resets when that procedure ends.
  • Module-level: Declare at the top of a module, outside any procedure, using Private or Dim. Procedures in that module can share it; it is not directly available to other modules.
  • Public: Declare at module level with Public to make it accessible to procedures across the VBA project, subject to project and naming rules. Use this sparingly because shared state can make code harder to maintain.
  • Static local: Use Static inside a procedure when a local variable should retain its value between calls, rather than being reinitialized each time.

For example, Private runCount As Long at the top of a standard module is shared by procedures in that module. By contrast, Dim runCount As Long inside a procedure is local to that procedure. When another procedure needs a value, passing it as an argument or returning it from a function is often clearer than making it public.

Common declaration mistakes and how to fix them

If VBA reports “Variable not defined,” check the spelling and confirm the variable is declared in a scope that the code can access. With Option Explicit, typos are caught during compilation, which is useful even in small macros.

If a variable behaves unexpectedly, check its type. A text value assigned to a numeric variable may cause a type mismatch, and a variable declared without an As clause becomes a Variant. Another frequent mistake is assuming every name in a comma-separated declaration receives the type written at the end; give every variable its own As clause.

For object variables, use Set when assigning and verify that the referenced workbook, worksheet, or range exists. An object variable that is still Nothing cannot be used as though it already referred to an Excel object. Finally, a variable’s scope does not make a worksheet reference safe: qualify worksheet and range references when the active workbook or sheet might change.

Frequently Asked Questions

What is the syntax to declare a variable in VBA?
Use Dim variableName As DataType, such as Dim itemCount As Long. Put it inside a procedure for local scope or at the module level for module-wide scope.

Do I have to declare variables in VBA?
VBA allows undeclared names by default, treating them as Variant variables in many situations. Add Option Explicit to require declarations and catch misspellings at compile time.

Should I use Integer or Long in VBA?
For most whole-number counters and Excel row or column indexes, use Long. VBA’s Integer has a narrower range and cannot represent all Excel row numbers.

What is the difference between Dim and Set?
Dim declares a variable. Set assigns an object reference to an already declared object variable, such as a Worksheet; it is not used to assign ordinary values.

How do I declare a global variable in VBA?
At the top of a module, outside any procedure, use Public variableName As DataType. A public variable can be shared across the project, but passing values between procedures is often easier to manage.

Can I declare multiple variables on one line?
Yes. Specify the type for each name, as in Dim a As Long, b As Long. In Dim a, b As Long, only b is a Long; a is a Variant.

In this article
  1. What a VBA variable declaration does
  2. How to declare a variable in the VBA editor
  3. Choosing a VBA data type
  4. Multiple variables, initialization, and Option Explicit
  5. Scope and lifetime: where a variable is available
  6. Common declaration mistakes and how to fix them
  7. Frequently Asked Questions