In VBA, Dim (short for Dimension) declares a variable and allocates memory for it, telling Excel what type of data you plan to store, such as a number, text, or date. You write it at the start of a procedure or module, like Dim rowCount As Long, and it is the most common way to create variables in macros.
Why the Word “Dim”?
The term comes from BASIC, the programming language VBA is based on. In early BASIC, Dim was used to set the dimensions of an array (e.g., Dim A(10) created a list with 11 slots). Over time, it became the standard keyword for declaring any variable, even a single one, so the name stuck. You will never see “Dimension” spelled out in VBA—the keyword is always the three letters.
What Dim Actually Does in Memory
When VBA runs a line like Dim total As Double, it reserves a small block of memory and gives it the name total. The As Double part tells Excel how many bytes to set aside and how to interpret the bits. A Long uses 4 bytes, a Double uses 8, a String uses a variable amount, and a Boolean uses 2. If you omit the type, VBA uses Variant, which can hold anything but uses more memory and runs slower. Declaring types is not just good style—it makes macros faster and prevents subtle bugs from unexpected data types.
How to Write a Dim Statement
The basic syntax is: Dim variableName As DataType. You can declare several variables on one line, but each needs its own As clause. A common mistake is writing Dim x, y As Long—this makes x a Variant and only y a Long. To make both Long, write Dim x As Long, y As Long. You can also assign a value on the same line: Dim counter As Long: counter = 0, though most people separate the declaration and assignment for clarity.
Where to Put Dim: Scope and Lifetime
Placement controls where the variable is visible and how long it lives:
- Inside a Sub or Function (procedure-level): the variable is created when the macro runs and destroyed when it ends. Other procedures cannot see it.
- At the top of a module, outside any procedure (module-level): the variable is available to all procedures in that module and keeps its value between calls, as long as the workbook is open.
- In a class module or user form: it becomes a property of that object, accessible with dot notation.
For a variable that must persist across macro runs, you would use a Static keyword inside a procedure instead of Dim, but that is a separate feature.
Common Data Types to Use With Dim
Choosing the right type prevents overflow errors and wasted memory. The most useful ones in Excel VBA:
String– text, e.g.,Dim name As StringLong– whole numbers from -2,147,483,648 to 2,147,483,647 (use this instead of Integer for row counts)Double– decimal numbers, e.g.,Dim price As DoubleBoolean– True or FalseDate– dates and timesRange– a cell or group of cells, e.g.,Dim rng As RangeWorksheet– a worksheet object
If you are unsure, use Variant, but know that it is slower and can cause type-mismatch errors when you compare values.
Dim vs. Set vs. Const: What’s the Difference?
Beginners often confuse these three. Dim declares a variable that can change value later. Const declares a named constant that cannot change, like Const pi As Double = 3.14159. Set is used to assign an object to a variable that was already declared with Dim—for example, Dim ws As Worksheet then Set ws = ThisWorkbook.Sheets(1). You cannot use Set for simple data types; you just use =. Also, Dim does not assign a value; it only reserves the name.
Common Errors and How to Avoid Them
Three frequent problems happen with Dim:
- Type mismatch (Error 13): You declared a variable as
Longbut tried to store text. Check the data type and convert withCStrorCLngif needed. - Variable not defined (Error 42): You used a variable name that was not declared, and you have
Option Explicitat the top of the module. Always declare every variable withDimbefore using it. - Forgetting to use
Setfor objects: If you declareDim rng As Rangeand then writerng = Range("A1"), you get an error. UseSet rng = Range("A1").
To catch undeclared variables automatically, add Option Explicit as the first line of each module. This forces you to declare everything, which reduces typos.
Example: A Simple Macro Using Dim
Here is a complete macro that sums values in column A and writes the result to a message box. Save a copy of your workbook before running any macro, because macros cannot be undone with Ctrl+Z.
Sub SumColumn()
Dim lastRow As Long
Dim total As Double
Dim i As Long
lastRow = Cells(Rows.Count, 1).End(xlUp).Row
total = 0
For i = 1 To lastRow
total = total + Cells(i, 1).Value
Next i
MsgBox "Total: " & total
End Sub
This declares lastRow to hold the row number, total for the running sum, and i as the loop counter. Without Dim, the macro would still run (if Option Explicit is off), but it would be slower and more error-prone.
Frequently Asked Questions
Do I have to use Dim in every macro? No, but it is strongly recommended. If you omit it and do not have Option Explicit, VBA creates a Variant variable on the fly. This works but makes debugging harder and performance worse.
Can I use Dim outside a procedure? Yes, at the top of a module. That makes the variable available to all procedures in that module. If you want it available to all modules, use Public instead of Dim.
What is the difference between Dim and ReDim? Dim declares a fixed-size array or a single variable. ReDim is used inside a procedure to resize an array that was already declared with Dim, changing its number of elements.
Is Dim case-sensitive? No, VBA is not case-sensitive. dim, DIM, and Dim all work, but the standard is Dim.
Can I declare multiple variables on one line? Yes, but you must repeat As for each type. Dim a As Long, b As String works; Dim a, b As Long only makes b a Long.
What happens if I don’t specify a type? The variable becomes a Variant, which can store any data. It uses more memory and can cause type-mismatch errors when you expect a specific type, so it is better to declare types explicitly.
Related
- B is for Butterfly Worksheet: Free Printables & Uses
- How to Calculate Battery Size for a Solar System
- Introduction to R Coding: Basics & First Steps
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- VBA to Compare Two Word Documents AutomaticallyTo compare two Word files with VBA, open both documents and call Word’s Application.CompareDocuments method. It creates a…
- VBA Contains String Function? How to Find Text with InStrYes—VBA can check whether one string contains another, but it does not have a built-in string method named…
- Excel VBA: Find a Cell with Specific Text in a RangeTo find a cell containing specific text with Excel VBA, use the Range.Find method. Set options such as…
- Excel VBA On Error Resume Next: Safe Use and ExamplesIn Excel VBA, On Error Resume Next tells a procedure to continue with the statement immediately after the…
- Excel Macro to Send Email: Setup, Code, and SafetyYes. In Excel for Microsoft 365 on Windows, a VBA macro can create an email in classic Outlook…
- Excel VBA: Loop Through Rows in a Range EfficientlyTo loop through every row in an Excel range with VBA, use For Each rowRange In dataRange.Rows when…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.