Declare a variable with Dim, a name and a type, then assign a value to it:
Dim total As Long
total = 250
Choose the type for what it holds: Long for whole numbers (rather than Integer, which overflows past 32,767), Double for decimals, Currency for money, String for text, Date for dates and Boolean for True or False. Object variables such as Range and Worksheet need Set: Set rng = Range("A1:A10").
Where you declare it sets its scope. Dim inside a procedure works only there. Private at the top of a module, above every procedure, covers that module, and Public at the top of a standard module covers every module in the workbook. Static inside a procedure keeps the value between calls.
Each variable on a line needs its own type. Dim a, b As Long makes only b a Long; a becomes a Variant. Write Dim a As Long, b As Long.
Put Option Explicit at the top of each module so a misspelt name stops the code instead of creating a new, empty variable. For dates, assign DateSerial(2018, 11, 10) rather than text such as "11/10/2018", which is read according to the PC’s regional settings.
VBA Variable
In VBA, a variable is like a storage box that is itself stored in your system, but it can store a value for you, and you can use that value in your code and change it if you want (as the name suggests, “VARIABLE” is something whose value is not fixed).
To declare a variable, you need to follow a simple procedure (VBA DIM):
- Use the keyword “Dim” at the start.
- Specify a name for the variable.
- Use the keyword “As” after the name.
- Specify the “Data Type” for the variable according to the value you want to assign to it.
Here we have used the name “startDate” and specified the data type “Date”. After declaring a variable, you can assign a value to it.
Dim startDate As Date startDate = #11/10/2018#
Now, whenever you use startDate in your code, VBA will use the date you have assigned to it. A date goes between hash signs (#) in the month/day/year format, so #11/10/2018# is November 10, 2018.
Data Types
In VBA, Data Types are basically the types of data that you need to specify while storing a value in a variable or a constant. For example, if you want to store a date in a variable, you must declare that variable with Date as its data type in the first place.
Data Types Explained
Following is the complete list of data types that you can use in VBA.
Written by
Puneet Gogia
Microsoft MVP — Excel · Founder, Excel Champs
Twelve years of teaching Excel, and a decade before that using it as a data analyst. Every tutorial here is written from a file I actually built.