“One man’s constant is another man’s variable.” – Alan Perlis
This post provides a complete guide to using the VBA Dim statement.
The first section provides a quick guide to using the Dim statement including examples and the format of the Dim statement.
The rest of the post provides the most complete guide you will find on the VBA Dim Statement.
If you are interested in declaring parameters then you can read about them here.
Contents
- 1 A Quick Guide to using the VBA Dim Statement
- 2 Useful Links
- 3
- 4 What is the VBA Dim Statement
- 5
- 6 Format of the VBA Dim Statement
- 7 How to Use Dim with Multiple Variables
- 8
- 9 Where Should I Put the Dim Statement?
- 10
- 11 Using Dim in Loops
- 12 Can I use Dim to Assign a Value?
- 13
- 14 Is Dim Actually Required?
- 15
- 16 Using Dim with Basic Variables
- 17 Using Dim with Variants
- 18 Using Dim with Objects
- 19 Using Dim with Arrays
- 20 Troubleshooting Dim Errors
- 21 Local versus Module versus Global Variables
- 22 Conclusion
- 23 What’s Next?
A Quick Guide to using the VBA Dim Statement
Description | Format | Example |
---|---|---|
Basic variable | Dim [variable name] As [Type] | Dim count As Long Dim amount As Currency Dim name As String Dim visible As Boolean |
Fixed String | Dim [variable name] As String * [size] | Dim s As String * 4 Dim t As String * 10 |
Variant | Dim [variable name] As Variant Dim [variable name] | Dim var As Variant Dim var |
Object using Dim and New | Dim [variable name] As New [object type] | Dim coll As New Collection Dim coll As New Class1 |
Object using Dim, Set and New | Dim [variable name] As [object type] Set [variable name] = New [object type] | Dim coll As Collection Set coll = New Collection Dim coll As Class1 Set coll = New Class1 |
Static array | Dim [variable name]([first] To [last] ) As [Type] | Dim arr(1 To 6) As Long |
Dynamic array | Dim [variable name]() As [Type] ReDim [variable name]([first] To [last]) | Dim arr() As Long ReDim arr(1 To 6) |
External Library (Early Binding)* | Dim [variable name] As New [item] | Dim dict As New Dictionary |
External Library (Early Binding using Set)* | Dim [variable name] As [item] Set [variable name] = New [item] | Dim dict As Dictionary Set dict = New Dictonary |
External Library (Late Binding) | Dim [variable name] As Object Set [variable name] = CreateObject("[library]") | Dim dict As Object Set dict = CreateObject("Scripting.Dictionary") |
*Note: Early binding requires that you add the reference file using Tools->References from the menu. See here for how to add the Dictonary reference.
Useful Links
Declaring parameters in a sub or function
Using Objects in VBA
VBA Arrays
VBA Collection
VBA Dictionary
VBA Workbook
VBA Worksheet
What is the VBA Dim Statement
The Dim keyword is short for Dimension. It is used to declare variables in VBA.
Declare means we are telling VBA about a variable we will use later.
There are four types of Dim statements. They are all pretty similar in terms of syntax.
They are:
- Basic variable
- Variant
- Object
- Array
The following is a brief description of each type:
-
- Basic variable – this variable type holds one value. These are the types such as Long, String, Date, Double, Currency.
-
- Variant – VBA decides at runtime which type will be used. You should avoid variants where possible but in certain cases it is a requirement to use them.
-
- Object – This is a variable that can have multiple methods(i.e. subs/functions) and multiple properties(i.e. values). There are 3 kinds:
- Excel objects such as the Workbook, Worksheet and Range objects.
- User objects created using Class Modules.
- External libraries such as the Dictionary.
- Object – This is a variable that can have multiple methods(i.e. subs/functions) and multiple properties(i.e. values). There are 3 kinds:
- Array – this is a group of variables or objects.
In the next section, we will look at the format of the VBA Dim statement with some examples of each.
In later sections we will look at each type in more detail.
Format of the VBA Dim Statement
The format of the Dim statement is shown below
' 1. BASIC VARIABLE ' Declaring a basic variable Dim [variable name] As [type] ' Declaring a fixed string Dim [variable name] As String * [size] ' 2. VARIANT Dim [variable name] As Variant Dim [variable name] ' 3. OBJECT ' Declaring an object Dim [variable name] As [type] ' Declaring and creating an object Dim [variable name] As New [type] ' Declaring an object using late binding Dim [variable name] As Object ' 4. ARRAY ' Declaring a static array Dim [variable name](first To last) As [type] ' Declaring a dynamic array Dim [variable name]() As [type]
Below are examples of using the different formats
' https://excelmacromastery.com/ Sub Examples() ' 1. BASIC VARIABLE ' Declaring a basic variable Dim name As String Dim count As Long Dim amount As Currency Dim eventdate As Date ' Declaring a fixed string Dim userid As String * 8 ' 2. VARIANT Dim var As Variant Dim var ' 3. OBJECT ' Declaring an object Dim sh As Worksheet Dim wk As Workbook Dim rg As Range ' Declaring and creating an object Dim coll1 As New Collection Dim o1 As New Class1 ' Declaring an object - create object below using Set Dim coll2 As Collection Dim o2 As Class1 Set coll2 = New Collection Set o2 = New Class1 ' Declaring and assigning using late binding Dim dict As Object Set dict = CreateObject("Scripting.Dictionary") ' 4. ARRAY ' Declaring a static array Dim arrScores(1 To 5) As Long Dim arrCountries(0 To 9) As String ' Declaring a dynamic array - set size below using ReDim Dim arrMarks() As Long Dim arrNames() As String ReDim arrMarks(1 To 10) As Long ReDim arrNames(1 To 10) As String End Sub
We will examine these different types of Dim statements in the later sections.
How to Use Dim with Multiple Variables
We can declare multiple variables in a single Dim statement
Dim name As String, age As Long, count As Long
If we leave out the type then VBA automatically sets the type to be a Variant. We will see more about Variant later.
' Amount is a variant Dim amount As Variant ' Amount is a variant Dim amount ' Address is a variant - name is a string Dim name As String, address ' name is a variant, address is a string Dim name, address As String
When you declare multiple variables you should specify the type of each one individually
Dim wk As Workbook, marks As Long, name As String
You can place as many variables as you like in one Dim statement but it is good to keep it to 3 or 4 for readability.
Where Should I Put the Dim Statement?
The Dim statement can be placed anywhere in a procedure. However, it must come before any line where the variable is used.
If the variable is used before the Dim statement then you will get a “variable not defined” error:
When it comes to the positioning your Dim statements you can do it in two main ways. You can place all your Dim statements at the top of the procedure:
' https://excelmacromastery.com/ Sub DimTop() ' Placing all the Dim statements at the top Dim count As Long, name As String, i As Long Dim wk As Workbook, sh As Worksheet, rg As Range Set wk = Workbooks.Open("C:\Docs\data.xlsx") Set sh = wk.Worksheets(1) Set rg = sh.Range("A1:A10") For i = 1 To rg.Rows.count count = rg.Value Debug.Print count Next i End Sub
OR you can declare the variables immediately before you use them:
' https://excelmacromastery.com/ Sub DimAsUsed() Dim wk As Workbook Set wk = Workbooks.Open("C:\Docs\data.xlsx") Dim sh As Worksheet Set sh = wk.Worksheets(1) Dim rg As Range Set rg = sh.Range("A1:A10") Dim i As Long, count As Long, name As String For i = 1 To rg.Rows.count count = rg.Value name = rg.Offset(0, 1).Value Debug.Print name, count Next i End Sub
I personally prefer the latter as it makes the code neater and it is easier to read, update and spot errors.
Using Dim in Loops
Placing a Dim statement in a Loop has no effect on the variable.
When VBA starts a Sub (or Function), the first thing it does is to create all the variables that have been declared in the Dim statements.
The following 2 pieces of code are almost the same. In the first, the variable Count is declared before the loop. In the second it is declared within the loop.
' https://excelmacromastery.com/ Sub CountOutsideLoop() Dim count As Long Dim i As Long For i = 1 To 3 count = count + 1 Next i ' count value will be 3 Debug.Print count End Sub
' https://excelmacromastery.com/ Sub CountInsideLoop() Dim i As Long For i = 1 To 3 Dim count As Long count = count + 1 Next i ' count value will be 3 Debug.Print count End Sub
The code will behave exactly the same because VBA will create the variables when it enters the sub.
Can I use Dim to Assign a Value?
In languages like C++, C# and Java, we can declare and assign variables on the same line
' C++ int i = 6 String name = "John"
We cannot do this in VBA. We can use the colon operator to place the declare and assign lines on the same line.
Dim count As Long: count = 6
We are not declaring and assigning in the same VBA line. What we are doing is placing these two lines(below) on one line in the editor. As far as VBA is concerned they are two separate lines as here:
Dim count As Long count = 6
Here we put 3 lines of code on one editor line using the colon:
count = 1: count = 2: Set wk = ThisWorkbook
There is really no advantage or disadvantage to assigning and declaring on one editor line. It comes down to a personal preference.
Is Dim Actually Required?
The answer is that it is not required. VBA does not require you to use the Dim Statement.
However, not using the Dim statement is a poor practice and can lead to lots of problems.
You can use a variable without first using the Dim statement. In this case the variable will automatically be a variant type.
This can lead to problems such as
- All variables are variants (see the Variant section for issues with this).
- Some variable errors will go undetected.
Because of these problems it is good practice to make using Dim mandatory in our code. We do this by using the Option Explicit statement.
Option Explicit
We can make Dim mandatory in a module by typing “Option Explicit” at the top of a module.
We can make this happen automatically in each new module by selecting Tools->Options from the menu and checking the box beside “Require Variable Declaration”. Then when you insert a new module, “Option Explicit” will be automatically added to the top.
Let’s look at some of the errors that may go undetected if we don’t use Dim.
Variable Errors
In the code below we use the Total variable without using a Dim statement
' https://excelmacromastery.com/ Sub NoDim() Total = 6 Total = Total + 1 Debug.Print Total End Sub
If we accidentally spell Total incorrectly then VBA will consider it a new variable.
In the code below we have misspelt the variable Total as Totall:
' https://excelmacromastery.com/ Sub NoDimError() Total = 6 ' The first Total is misspelt Totall = Total + 1 ' This will print 6 instead of 7 Debug.Print Total End Sub
VBA will not detect any error in the code and an incorrect value will be printed.
Let’s add Option Explicit and try the above code again
' https://excelmacromastery.com/ Option Explicit Sub NoDimError() Total = 6 ' The first Total is misspelt Totall = Total + 1 ' This will print 6 instead of 7 Debug.Print Total End Sub
Now when we run the code we will get the “Variable not defined” error. To stop this error appearing we must use Dim for each variable we want to use.
When we add the Dim statement for Total and run the code we will now get an error telling us that the misspelt Totall was not defined.
This is really useful as it helps us find an error that would have otherwise gone undetected.
Keyword Misspelt Error
Here is a second example which is more subtle.
When the following code runs it should change the font in cell A1 to blue.
However, when the code runs nothing happens.
' https://excelmacromastery.com/ Sub SetColor() Sheet1.Range("A1").Font.Color = rgblue End Sub
The error here is that rgblue should be rgbBlue. If you add Option Explicit to the module, the error “variable not defined” will appear. This makes solving the problem much easier.
These two examples are very simple. If you have a lot of code then errors like this can be a nightmare to track down.
Using Dim with Basic Variables
VBA has the same basic variable types that are used in the Excel Spreadsheet.
You can see a list of all the VBA variable types here.
However, most of the time you will use the following ones
Type | Storage | Range | Description |
---|---|---|---|
Boolean | 2 bytes | True or False | This variable can be either True or False. |
Long | 4 bytes | -2,147,483,648 to 2,147,483,647 | Long is short for Long Integer. Use this instead of the Integer* type. |
Currency | 8 bytes | -1.79769313486231E308 to-4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values | Similar to Double but has only 4 decimal places |
Double | 8 bytes | -922,337,203,685,477.5808 to 922,337,203,685,477.5807 | |
Date | 8 bytes | January 1, 100 to December 31, 9999 | |
String | varies | 0 to approximately 2 billion | Holds text. |
*Originally we would use the Long type instead of Integer because the Integer was 16-bit and so the range was -32,768 to 32,767 which is quite small for a lot of the uses of integer.
However on a 32 bit(or higher) system the Integer is automatically converted to a Long. As Windows has been 32 bit since Windows 95\NT there is no point in using an Integer.
In a nutshell, always use Long for an integer type in VBA.
Fixed String Type
There is one unusual basic variable type in VBA that you may not be familiar with.
This is the fixed string type. When we create a normal string in VBA we can add text and VBA will automatically resize the string for us
' https://excelmacromastery.com/ Sub StringType() Dim s As String ' s is "John Smith" s = "John Smith" ' s is "Tom" s = "Tom" End Sub
A fixed string is never resized. This string will always be the same size no matter what you assign to it
Here are some examples
' https://excelmacromastery.com/ Sub FixedString() Dim s As String * 4 ' s is "John" s = "John Smith" ' s = "Tom " s = "Tom" End Sub
Using Dim with Variants
When we declare a variable to be a variant, VBA will decide at runtime which variable type it should be.
We declare variants as follows
' Both are variants Dim count Dim count As Variant
This sounds like a great idea in theory. No more worrying about the variable type
' https://excelmacromastery.com/ Sub UsingVariants() Dim count As Variant count = 7 count = "John" count = #12/1/2018# End Sub
However, using variants is poor practice and this is why:
- Runtime Errors – VBA will not notice incorrect type errors(i.e. Data Mismatch).
- Compile Errors – VBA cannot detect compile errors.
- Intellisense is not available.
- Size – A variant is set to 16 bytes which is the largest variable type
Runtime Errors
Errors are your friend!
They may be annoying and frustrating when they happen but they are alerting you to future problems which may not be so easy to find.
The Type Mismatch error alerts you when incorrect data is used.
For example. Imagine we have a sheet of student marks. If someone accidentally(or deliberately) replaces a mark with text then the data is invalid.
If we use a variant to store marks then no error will occur:
' https://excelmacromastery.com/ Sub MarksVariant() Dim mark As Variant Dim i As Long For i = 1 To 10 ' Read the mark mark = Sheet1.Range("A" & i).Value Next End Sub
This is not good because there is an error with your data and you are not aware of it.
If you make the variable Long then VBA will alert you with a “Type Mismatch” error if the values are text.
' https://excelmacromastery.com/ Sub MarksLong() Dim mark As Long Dim i As Long For i = 1 To 10 ' Read the mark mark = Sheet1.Range("A" & i).Value Next End Sub
Compile Errors
Using the compiler to check for errors is very efficient. It will check all of your code for problems before you run it. You use the compiler by selecting Debug->Compile VBAProject from the menu.
In the following code, there is an error. The Square function expects a long integer but we are passing a string(i.e. the name variable):
' https://excelmacromastery.com/ Sub CompileError() Dim name As String Debug.Print Square(name) End Sub Function Square(value As Long) As Long Square = value * value End Function
If we use Debug->Compile on this code, VBA will show us an error:
This is good news as we can fix this error right away. However, if we declare the value parameter as a variant:
Function Square(value As Variant) As Long Square = value * value End Function
then Debug.Compile will not treat this as an error. The error is still there but it is undetected.
Accessing the Intellisense
The Intellisense is an amazing feature of VBA. It gives you the available options based on the type you have created.
Imagine you declare a worksheet variable using Dim
Dim wk As Workbook
When you use the variable wk with a decimal point, VBA will automatically display the available options for the variable.
You can see the Intellisense in the screenshot below
If you use Variant as a type then the Intellisense will not be available
Dim wk As Variant
This is because VBA will not know the variable type until runtime.
Variant Size
The size of a variant is 16 bytes. If the variable is going to be a long then it would only take up 4 bytes. You can see that this is not very efficient.
However, unlike the 1990’s where this would be an issue, we now have computers with lots of memory and it is unlikely you will notice an inefficiency unless you are using a huge amount of variables.
Using Dim with Objects
If you don’t know what Objects are then you can read my article about VBA Objects here.
There are 3 types of objects:
- Excel objects
- Class Module objects
- External library objects
Note: The VBA Collection object is used in a similar way to how we use Class Module object. We use new to create it.
Let’s look at each of these in turn.
Excel objects
Excel objects such as the Workbook, Worksheet, Range, etc. do not use New because they are automatically created by Excel. See When New is not required.
When a workbook is created or opened then Excel automatically creates the associated object.
For example, in the code below we open a workbook. VBA will create the object and the Open function will return a workbook which we can store in a variable
' https://excelmacromastery.com/ Sub OpenWorkbook() Dim wk As Workbook Set wk = Workbooks.Open("C:\Docs\data.xlsx") End Sub
If we create a new worksheet, a similar thing happens. VBA will automatically create it and provide use access to the object.
' https://excelmacromastery.com/ Sub AddSheet() Dim sh As Worksheet Set sh = ThisWorkbook.Worksheets.Add End Sub
We don’t need to use the New keyword for these Excel objects.
We just assign the variable to the function that either creates a new object or that gives us access to an existing one.
Here are some examples of assigning the Workbook, Worksheet and range variables:
' https://excelmacromastery.com/ Sub DimWorkbook() Dim wk As Workbook ' assign wk to a new workbook Set wk = Workbooks.Add ' assign wk to the first workbook opened Set wk = Workbooks(1) ' assign wk to The workbook Data.xlsx Set wk = Workbooks("Data.xlsx") ' assign wk to the active workbook Set wk = ActiveWorkbook End Sub
' https://excelmacromastery.com/ Sub DimWorksheet() Dim sh As Worksheet ' Assign sh to a new worksheet Set sh = ThisWorkbook.Worksheets.Add ' Assign sh to the leftmost worksheet Set sh = ThisWorkbook.Worksheets(1) ' Assign sh to a worksheet called Customers Set sh = ThisWorkbook.Worksheets("Customers") ' Assign sh to the active worksheet Set sh = ActiveSheet End Sub
' https://excelmacromastery.com/ Sub DimRange() ' Get the customer worksheet Dim sh As Worksheet Set sh = ThisWorkbook.Worksheets("Customers") ' Declare the range variable Dim rg As Range ' Assign rg to range A1 Set rg = sh.Range("A1") ' Assign rg to range B4 to F10 Set rg = sh.Range("B4:F10") ' Assign rg to range E1 Set rg = sh.Cells(1, 5) End Sub
If you want to know more about these objects you can check out these articles: VBA Workbook, VBA Worksheet and VBA Ranges and Cells.
Using Dim with Class Module Objects
In VBA we use Class Modules to create our own custom objects. You can read all about Class Modules here.
If we are creating an object then we need to use the New keyword.
We can do this in the Dim statement or in the Set statement.
The following code creates an object using the New keyword in the Dim statement:
' Declare and create Dim o As New class1 Dim coll As New Collection
Using New in a Dim statement means that exactly one object will be created each time our code runs.
Using Set gives us more flexibility. We can create many objects from one variable. We can also create an object based on a condition.
This following code shows how we create a Class Module object using Set.
(To create a Class Module, go to the project window, right-click on the appropiate workbook and select “Insert Class Module”. See Creating a Simple Class Module for more details.)
' Declare only Dim o As Class1 ' Create using Set Set o = New Class1
Let’s look at an example of using Set. In the code below we want to read through a range of data. We only create an object if the value is greater than 50.
We use Set to create the Class1 object. This is because the number of objects we need depends on the number of values over 50.
' https://excelmacromastery.com/ Sub UsingSet() ' Declare a Class1 object variable Dim o As Class1 ' Read a range Dim i As Long For i = 1 To 10 If Sheet1.Range("A" & i).Value > 50 Then ' Create object if condition met Set o = New Class1 End If Next i End Sub
I’ve kept this example simple for clarity. In a real-world version of this code we would fill the Class Module object with data and add it to a data structure like a Collection or Dictionary.
Here is an example of a real-world version based on the data below:
' Class Module - clsStudent Public Name As String Public Subject As String ' Standard Module ' https://excelmacromastery.com/ Sub ReadMarks() ' Create a collection to store the objects Dim coll As New Collection ' Current Region gets the adjacent data Dim rg As Range Set rg = Sheet1.Range("A1").CurrentRegion Dim i As Long, oStudent As clsStudent For i = 2 To rg.Rows.Count ' Check value If rg.Cells(i, 1).Value > 50 Then ' Create the new object Set oStudent = New clsStudent ' Read data to the student object oStudent.Name = rg.Cells(i, 2).Value oStudent.Subject = rg.Cells(i, 3).Value ' add the object to the collection coll.Add oStudent End If Next i ' Print the data to the Immediate Window to test it Dim oData As clsStudent For Each oData In coll Debug.Print oData.Name & " studies " & oData.Subject Next oData End Sub
To learn more about Set you can check out here.
Objects from an External Library
A really useful thing we can do with VBA is to access external libraries. This opens up a whole new world to what we can do.
Examples are the Access, Outlook and Word libraries that allow us to communicate with these applications.
We can use libraries for different types of data structures such as the Dictionary, the Arraylist, Stack and Queue.
There are libraries for scraping a website (Microsoft HTML Object Library), using Regular Expressions (Microsoft VBScript Regular Expressions) and many other tasks.
We can create these objects in two ways:
- Early Binding
- Late Binding
Let’s look at these in turn.
Early Binding
Early binding means that we add a reference file. Once this file is added we can treat the object like a class module object.
We add a reference using Tools->Reference and then we check the appropriate file in the list.
For example, to use the Dictionary we place a check on “Microsoft Scripting Runtime”:
Once we have the reference added we can use the Dictionary like a class module object
' https://excelmacromastery.com/ Sub EarlyBinding() ' Use Dim only Dim dict1 As New Dictionary ' Use Dim and Set Dim dict2 As Dictionary Set dict2 = New Dictionary End Sub
The advantage of early binding is that we have access to the Intellisense. The disadvantage is that it may cause conflict issues on other computers.
The best thing to do is to use early binding when writing the code and then use late binding if distributing your code to other users.
Late Binding
Late binding means that we create the object at runtime.
We declare the variable as an “Object” type. Then we use CreateObject to create the object.
' https://excelmacromastery.com/ Sub LateBinding() Dim dict As Object Set dict = CreateObject("Scripting.Dictionary") End Sub
Using Dim with Arrays
There are two types of arrays in VBA. They are:
- Static – the array size is set in the Dim statement and it cannot change.
- Dynamic – the array size is not set in the Dim statement. It is set later using the ReDim statement.
' STATIC ARRAY ' Stores 7 Longs - 0 to 6 Dim arrLong(0 To 6) As Long ' Stores 7 Strings - 0 to 6 Dim arrLong(6) As String
A dynamic array gives us much more flexibility. We can set the size while the code is running.
We declare a dynamic array using the Dim statement and we set the size later using ReDim.
' DYNAMIC ARRAY ' Declare the variable Dim arrLong() As Long ' Set the size ReDim arrLong(0 To 6) As Long
Using ReDim
The big difference between Dim and ReDim is that we can use a variable in the ReDim statement. In the Dim statement, the size must be a constant value.
' https://excelmacromastery.com/ Sub UserSet() ' Declare the variable Dim arrLong() As Long ' Ask the user for the size Dim size As Long size = InputBox("Please enter the size of the array.", Default:=1) ' Set the size based on the user input ReDim arrLong(0 To size) As Long End Sub
We can actually use the Redim Statement without having first used the Dim statement.
In the first example you can see that we use Dim:
' https://excelmacromastery.com/ Sub UsingDimReDim() ' Using Dim Dim arr() As String ReDim arr(1 To 5) As String arr(1) = "Apple" arr(5) = "Orange" End Sub
In the second example we don’t use Dim:
' https://excelmacromastery.com/ Sub UsingReDimOnly() ' Using ReDim only ReDim arr(1 To 5) As String arr(1) = "Apple" arr(5) = "Orange" End Sub
The advantage is that you don’t need the Dim statement. The disadvantage is that it may confuse someone reading your code. Either way it doesn’t make much difference.
You can use the Preserve keyword with ReDim to keep existing data while you resize an array. You can read more about this here here.
You can find everything you need to know about arrays in VBA here.
Troubleshooting Dim Errors
The table below shows the errors that you may encounter when using Dim. See VBA Errors for an explanation of the different error types.
Error | Type | Cause |
---|---|---|
Array already dimensioned | Compile | Using Redim on an array that is static |
Expected: identifier | Syntax | Using a reserved word as the variable name |
Expected: New of type name | Syntax | The type is missing from the Dim statement |
Object variable or With block variable not set | Runtime | New was not used to create the object(see Creating an Object) |
Object variable or With block variable not set | Runtime | Set was not used to assign an object variable. |
User-defined type not defined | Compile | The type is not recognised. Can happen if a reference file is not added under Tools->Reference or the Class Module name is spelled wrong. |
Statement invalid outside Type block | Compile | Variable name is missing from the Dim statement |
Variable not defined | Compile | The variable is used before the Dim line. |
Local versus Module versus Global Variables
When we use Dim in a procedure (i.e. a Sub or Function), it is considered to be local. This means it is only available in the procedure where it is used.
The following are the different types of variables found in VBA:
- Local variables are variables that are available to the procedure only. Local variables are declared using the Dim keyword.
- Module variables are variables that are only available in the current module only. Module variables are declared using the Private keyword.
- Global variables are variables that are available to the entire project. Global variables are declared using the Public keyword.
In the code below we have declared count as a global variable:
' Global ' https://excelmacromastery.com/ Public count As Long Sub UseCount1() count = 6 End Sub Sub UseCount2() count = 4 End Sub
What happens if we have a global variable and a local variable with the same name?
It doesn’t actually cause an error. VBA gives the local declaration precedence:
' https://excelmacromastery.com/ ' Global Public count As Long Sub UseCount() ' Local Dim count As Long ' Refers to the local count count = 6 End Sub
Having a situation like this can only lead to trouble as it is difficult to track which count is being used.
In general global variables should be avoided. They make the code very difficult to read because their values can be changed anywhere in the code. This makes errors difficult to spot and resolve.
The one use of a global variable is retaining a value between code runs. This can be useful for certain applications where you want to ‘remember’ a value after the code has stopped running.
In the code below we have a sub called Update. Each time we run the Update sub(using Run->Run Sub from the menu or F5) it will add 5 to the amount variable and print the result to the Immediate Window(Ctrl + G to view this window):
Public amount As Long Sub Update() amount = amount + 5 Debug.Print "Update: " & amount End Sub
The results are:
First run: amount = 5
Second run: amount = 10
Third run: amount = 15
and so on.
If we want to clear all global variable values then we can use the End keyword. Note that the End keyword will stop the code and reset all variables so you should only use it as the last line in your code.
Here is an example of using the End keyword:
Sub ResetAllGlobals() End ' Resets all variables and ends the current code run End Sub
Dim versus Private versus Public
We can declare variables using Public, Private and Dim. In some cases, they can be used interchangeably.
However, the following is the convention we use for each of the declaration keywords:
- Dim – used to declare local variables i.e. available only in the current procedure.
- Private – used to declare module variables and procedures. These are available within the current module only.
- Public – used to declare global variables and procedures. These are available throughout the project.
- Global(obsolete) – an older and obsolete version of Public. Can only be used in standard modules. It only exists for backward compatibility.
Note the Public and Private keywords are also used within Class Modules.
Conclusion
This concludes the article on the VBA Dim Statement. If you have any questions or thoughts then please let me know in the comments below.
What’s Next?
Free VBA Tutorial If you are new to VBA or you want to sharpen your existing VBA skills then why not try out the The Ultimate VBA Tutorial.
Related Training: Get full access to the Excel VBA training webinars and all the tutorials.
(NOTE: Planning to build or manage a VBA Application? Learn how to build 10 Excel VBA applications from scratch.)
Hi Paul,
in the description 3.III it appears there is a sentence within a sentence…III. External librDeclaring a static arrayaries such as the Dictionary. Can you clarify this section please?
Thanks for sharing your expertise!
Updated:-)
Hi Paul
Appears to be a proofing error here… Please clarify
For example. Imagine we have a sheet of student marks. If someone accidentally There are 3 types of objects(or deliberately) replaces a mark with text then the data is invalid.
Hi Laura,
It was a copy/paste error. I’ve updated the post.
Hello It is not discussed what happens that we use class or collection. Can we go by some other methods instead of creating class or objects?
I think the concept of class or collection is difficult for beginners.
I saw some links for complete VBA Class module, but the fact is that I have limited time and beginner can absorb some amount of knowledge only. They can’t learn all the material in one shot. Anyway, I am trying to catch up with these.
This code gave me errors:
Sub UsingSet()
‘ Declare a Class1 object variable
Dim o As Class1
‘ Read a range
Dim i As Long
For i = 1 To 10
If Sheet1.Range(“A” & i).Value > 50 Then
‘ Create object if condition met
Set o = New Class1
End If
Next i
End Sub
Al
I am learning VBA and I believe in a life time learning. I can spend time on this since I am home, later on, in the future that won’t be possible, I don’t know how to catch up with these materials. Is there any advise how to break each lesson for myself?
———————–
Yesterday I received some materials on worksheet and workbook material and the line of code
codeNameFrom…. was giving error and it was saying undefined.
===============
Hi,
If you are a beginner then I wouldn’t worry about Collections and Class Modules for the moment.
The most important thing to concentrate on is ranges/cells, the workbook and the worksheet.
I have created a tutorial aimed at complete VBA beginner here.
What error message are you getting in the code?
Awesome explanation of Early vs Late Binding with advice on when to use each. Now I get it; thanks!
You’re welcome.
Hi Paul, this is an excellent “Reference Source” – I have relearnt a lot that I had taken for granted in VBA coding. Thanks a lot.
John
You’re welcome John. Glad you found it useful.
I will study this body of work that you have provided to the “World Of Paul”. You are a wonderful talent.
Best
Dick
Thanks Dick.
Paul,
Thank’s for your useful clarifications.
I have notice a copy/paste error in the comments of the first example in “Fixed String Type” section (i.e.: Dim s As String); shouldn’t it be:
‘ s is “John Smith” instead of ‘ s is “John”
‘ s is “Tom” instead of ‘ s is “Tom ”
Alike David L Bedford, I also appreciated the Early vs Late Binding use recommendation.
As well as the “Fixed String Type” I didn’t have the opportunity to use yet.
Best (from France).
Hi Laurent.
Glad you like the post. Thank’s for pointing out the issues. I have updated the post.
Paul
Great article!
Still supported but old is the idea of using a character suffix instead of spelling out the type
Instead of:
dim i as integer
You can say
dim i%
You do not need the “As Integer”
How I usually code when I need to dimension many of the same type of variable is I use the type spelled out only on the last variable and the character suffix for the others, something like this:
dim i%, j%, k as Integer
VBA will make the variables all integers in the above example
I never use it for just one variable alone because saying for example “As Integer” is clearer. That is why the last variable, I will always spell out.
There are only a few possible suffixes:
Currency: @
Double: #
Integer: %
Long: &
Single: !
String: $
Thanks for that information Dan, very interesting.
I actually remember using $ for strings when I first started using Basic on a home computer many moons ago.
Paul
Awesome post, thanks Paul!
Regarding early binding, I was wondering what are your thoughts on adding the reference programmatically.
Eg. For the Microsoft Scripting Runtime Library:
wb.VBProject.References.AddFromGuid “{420B2830-E718-11CF-893D-00A0C9054228}”, 1, 0
Hi Martin,
It depends on what your are trying to achieve. I did this kind of COM programming many years ago through C++.
Regards
Paul
Hi Paul
A point to note, a Variant object acts as a Double when used numerically.
Good simple explanation of early vs. late bindings 🙂
The reason it’s best practice to use Late bindings is that it makes code transportable across different versions of Excel. A module written using Office 2016 that accesses Word or Access objects may not work on a PC with Office 2007 if early binding is used as the incorrect references may be set. Late binding avoids this as Excel always uses the latest available objects for the version of Office on the PC on which the VBA is running.
Way beyond the interest of most people, but I saw you’ve used C in the past; what is a LongPtr data type for? I was hoping it was a true pointer, which is useful for VBA functions which for example parse cell formulae.
I initially thought it was the Excel version of a Pointer variable which doesn’t have a value in itself, but the excel documentation suggests it’s a version of Long or LongLong. (I haven’t used C pointers, my pointer knowledge is from pascal, way before C was around)
Hi Johnny,
Late binding uses COM(component object modeling) technology to interrogate the files at runtime. This makes it more flexible and allows it to select the latest version of a function. I did some work with COM in the 1990s – something I hope to never repeat:-)
LongPtr is used to make the code portable of 32/64 bit systems. It is becomes a long integer in a 32-bit system and longlong integer in a 64-bit system.
Paul
Hi,
Thanks for the post, very useful.
Can a declared dim be used over several worksheets, within a same sub?
Hi Lauren,
I’m not clear what you mean by “used over several worksheets”.
You can use dim to declare multiple worksheet variables if that’s what you’re asking.
Paul
Hello Paul,
Paul, thank you for your awesome work. My question with regard to “dimming” variables: Is it possible to let a variable declaration pick up a name from e.g. the contents of a cell, such as: Dim Range(“A1″).Text as variant”, where A1 contains a String? I am looking desperately for a way to name variables automatically based on the Headers of Columns in my worksheet. A Hint of yours would be greatly appreciated. Thank you in advance. Regards, hgl
What you are talking about is Refection. VBA doesn’t support this but if you use google you can see some ways that are used to get around it.
Hi Paul,
thank you for this great tutorials and concepts. I hope you expand the topics similar with this VBA and Excel tp VBA and Access-SQL Database concepts.
Thank you!
Kind regards,
Aaron =)
Maybe in the future Aaron but I have no plans at the moment.
In the article there is a mistake in the CountInsideLoop function.
You did put ‘ count value will be 3, and this is not correct
‘ count value will be 1 instead
Thanks for your web is perfect
Best Regards a happy New Year
It is correct. The value of count will be 1 when you run this code.
Thanks, Paul for your awesome works. Is it possible to declare a public variable and give it a value then use it in different subs.
Thanks again
It is possible but it’s considered a poor practice to use global variables.
In the two two examples in “Where Should I Put the Dim Statement? ” they fail at line in the loop segment “count = rg.Value” with the error message “type mismatch”. Is that because I am still using Excel 2007?
No. Most likely the value you are reading from the range is text rather than a number which is expected.
Thank you for your reply but I am still puzzled. I opened a new excel workook and populated sheet1 range A1:A10 with the numbers 1 to 10. I then copied your example DimTop to a new module and modified the first set statement to “Set wk = ThisWorkbook” and ran the sub and still got the error message. I then replaced the For i loop with a For Each loop and it ran without error. I am missing something fundamental here but cannot see what it is. A copy of each of my subs is below.
Option Explicit
Sub DimTop1()
‘ Placing all the Dim statements at the top
Dim count As Long, name As String, i As Long
Dim wk As Workbook, sh As Worksheet, rg As Range
Set wk = ThisWorkbook
Set sh = wk.Worksheets(1)
Set rg = sh.Range(“A1:A10”)
For i = 1 To rg.Rows.count
count = rg.Value
Debug.Print count
Next i
End Sub
Sub DimTop2()
‘ Placing all the Dim statements at the top
Dim count As Long, name As String, i As Long
Dim wk As Workbook, sh As Worksheet, rg As Range
Set wk = ThisWorkbook
Set sh = wk.Worksheets(1)
Set rg = sh.Range(“A1:A10”)
For Each rg In Range(“A1:A10”)
count = rg.Value
Debug.Print count
Next rg
End Sub
In DimTop1() rg is a range of 10 elements but you dont define with element aut of rg is required
But in DimTop2 () rg is already a certain element out of Range(“A1:A10″)
Since posting the above I have noted two things.
1.If the posting is copied into a new module you must relace the single and double quote marks. Somehow in the copying process the correct characters have been replaced with a similar looking but different charactes.
2. In Sub DimTop1() If the first line in the For I loop is replaced with count = rg.Cells(i, 1). the error no longer occurs. The addition of .Cells(i,1) perhaps satifies the compiler with a value for i.
I was having the same issue and… this worked for me as well.
I think it would be cool to be able to group DIM variables. For example, say i, j, and k are integers, instead of:
DIM i As Integer, j As Integer, k As Integer
You’d write:
Dim (i, j, k) As Integer
Not only would it save space (imagine longer variable names), but you could group like concepts. In this case, these three are being used for counting.
Hello,
I have a Question about the one Declaration you have In the section:
“How to Use Dim with Multiple Variables”
– – > Dim wk As Workbook, marks As Count, name As String
Second example I see ( Mark As Count ) I was looking online to find a reference to what that Data Type is.
But am not able to find it can explain why Also what would be nice to have a Index with all the Variable\Object.
Hi Geovanni,
That is a typo. It should read “As Long”. I have updated the post.
How would I declare a single column number e.g. my intended code would be say Range(“M” + i).
My reference code would be say Range (sColumn + i).
How would I declare the Dim for SColumn, I have tried as String, as Range, as Variant. I actually have an input box
sColumn = InputBox(“Which column must the range/row be copied to?:”), so I tried String as “M”, or just M, I have tried setting as range, it doesn’t accept any
Thx, would really appreciate your help
I’m not clear on your question. You can use Cells instead of range. Its takes Row and Column as Parameters e.g. Cells(1,5) is E1.
It’s a great tutorial! Easy to understand, very useful to the beginner like me.
Thanks Paul.
Paul, this is VERY helpful and I thank you (again) for such a great post. I have a compound question on dim/functions but want to make sure I understand this first.
Square(value As Variant) As Long
is used above to illustrate how an error will be thrown. I think I understand that as name was being passed and name was string, but now it’s going into value (right)? and value being a variant is the issue.
In the above
1) if you are passing a variable to a function (name in this case) why would you give it a different name in the function?
2) is Square being dimensioned as Long?
Thanks Jerry,
1) the reason is that the function could be call from many different places that have different variables names e.g.
Call Square(value)
Call Square(total)
Call Square(10)
2) “Square() As Long” in your means that the function “Square” will return the result as a long integer.
Objects from an External Library mentions stack and queue. Do you discuss this/these in any of your training? I’ve looked at ArrayList and I’ve googled them.
Hi Jerry,
Stack and Queue belong to the same external library as ArrayList. I haven’t covered them because the library no longer supports intellisense which makes it tricky to use unless you’re an advanced user. A second issue is that application requires the correct version of .Net to use it.
If you need to use them it is better to create your own version using the Collection.
very clear and good article easy to understand. Thank you
Thanks