Ozgrid, Experts in Microsoft Excel Spreadsheets

Excel VBA Variables


Using Variables in Excel VBA Macro Code

Got any Excel Questions? Excel Help .

See Also: Lifetime and Scope of Variables


A Variable is used to store temporary information that is used for execution within the Procedure, Module or Workbook.  Before we go into some detail of Variables, there are a few important rules that you must know about.

1) A Variable name must Start with a letter and not a number.  Numbers can be included within the name, but not as the first character.
2) A Variable name can be no longer than 250 characters.
3) A Variable name cannot be the same as any one of Excel's key words.  By this, I mean you cannot name a Variable with such names as Sheet, Worksheet etc.
4) All Variables must consist of one continuous string of characters only.  You can separate words by either capitalising the first letter of each word, or by using the underscore characters if you prefer.

You can name variables with any valid name you wish. For Example you could name a variable "David" and then declare it as any one of the data types shown below. However, it is good practice to formalize some sort of naming convention. This way when reading back your code you can tell at a glance what data type the variable is. An example of this could be the system I use! If you were to declare a variable as a Boolean (shown in table below) I may use: bIsOpen I might then use this Boolean variable to check if a Workbook is open or not. The "b" stands for Boolean and the "IsOpen" will remind me that I am checking if something is open.

You may see code that uses letters only as variables, this is bad programming and should be avoided. Trying to read code that has loads of single letters only can (and usually does) cause grief.

Variables can be declared as any one of the following data types:

Byte data type
A data type used to hold positive integer numbers ranging from 0 to 255. Byte variables are stored as single, unsigned 8-bit (1-byte) numbers.

Boolean data type
A data type with only two possible values, True (-1) or False (0). Boolean variables are stored as 16-bit (2-byte) numbers.

Integer data type
A data type that holds integer variables stored as 2-byte whole numbers in the range -32,768 to 32,767. The Integer data type is also used to represent enumerated values. The percent sign (%) type-declaration character represents an Integer in Visual Basic.

Long data type
A 4-byte integer ranging in value from -2,147,483,648 to 2,147,483,647. The ampersand (&) type-declaration character represents a Long in Visual Basic.

Currency data type
A data type with a range of -922,337,203,685,477.5808 to 922,337,203,685,477.5807. Use this data type for calculations involving money and for fixed-point calculations where accuracy is particularly important. The at sign (@) type-declaration character represents Currency in Visual Basic.

Single data type
A data type that stores single-precision floating-point variables as 32-bit (2-byte) floating-point numbers, ranging in value from -3.402823E38 to -1.401298E-45 for negative values, and 1.401298E-45 to 3.402823E38 for positive values. The exclamation point (!) type-declaration character represents a Single in Visual Basic.

Double data type
A data type that holds double-precision floating-point numbers as 64-bit numbers in the range -1.79769313486232E308 to -4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values. The number sign (#) type-declaration character represents the Double in Visual Basic.

Date data type
A data type used to store dates and times as a real number. Date variables are stored as 64-bit (8-byte) numbers. The value to the left of the decimal represents a date, and the value to the right of the decimal represents a time.

String data type
A data type consisting of a sequence of contiguous characters that represent the characters themselves rather than their numeric values. A String can include letters, numbers, spaces, and punctuation. The String data type can store fixed-length strings ranging in length from 0 to approximately 63K characters and dynamic strings ranging in length from 0 to approximately 2 billion characters. The dollar sign ($) type-declaration character represents a String in Visual Basic.

Object data type
A data type that represents any Object reference. Object variables are stored as 32-bit (4-byte) addresses that refer to objects.

Variant data type
Variant data type A special data type that can contain numeric, string, or date data as well as the special values Empty and Null. The Variant data type has a numeric storage size of 16 bytes and can contain data up to the range of a Decimal, or a character storage size of 22 bytes (plus string length), and can store any character text. The VarType function defines how the data in a Variant is treated. All variables become Variant data types if not explicitly declared as some other data type.

Why we use variables

Excel will still allow us to run our code without using variables, it is not a must! But having said this it is very bad programming to not use variables. You could quite easily just assign a value, string or whatever each time you need it, but it would mean:

1) Your code would become hard to follow (even for yourself)
2) Excel would constantly need to look for the value elsewhere.
3) Editing your code would become awkward.

Let's use an example to highlight the above

Sub NoVariable()

	Range("A1").Value = Range("B2").Value

	Range("A2").Value = Range("B2").Value * 2

	Range("A3").Value = Range("B2").Value * 4

	Range("B2").Value = Range("B2").Value * 5

End Sub

In the above code, Excel would need to retrieve the value from cell B2 five times. It would also mean if we had many other procedures using the same value i.e B2, it would need to retrieve it's value even more times.

There is a lot of editing to be done if we were to change from wanting B2 value to say, B5 value. It is messy code.

Let's now use a variable to store the value of cell B2!

Sub WithVariable()

Dim iMyValue as Integer

	iMyValue = Range("B2").Value

	Range("A1").Value = iMyValue 

	Range("A2").Value = iMyValue * 2

	Range("A3").Value = iMyValue * 4

	Range("B2").Value = iMyValue * 5

End Sub

In the above code Excel only needs to retrieve the value of cell B2 once.
To edit our code we only need to change it in one place.
It is easier to read.

You might be thinking that there is no big difference in the above 2 examples, and to a point you would be correct. But what you must realize is, most VBA projects will consist of hundreds (if not thousands) of lines of code. They would also contain a lot more than one procedure. If you had 2 average size VBA projects, one using variables and one without, the one using variables would run far more efficiently!

Declaring Variables
To declare a variable we use the word "Dim" (short for Dimension) followed by our chosen variable name then the word "As" followed by the variable type. So a variable dimmed as a String could look like:

Dim sMyWord As String

You will notice that as soon as we type the word As, Excel will display a drop-down list of all variables.

The default value for any Numeric type Variable is zero.  
The default value for any String type variable is "" (empty text).  
The default value for an Object type Variable is Nothing.  While the default value for an Object type Variable is Nothing, Excel will still reserve space in memory for it.

To assign a value to a Numeric or String type Variable, you simply use your Variable name, followed by the equals sign (=) and then the String or Numeric type.  eg:

Sub ParseValue()

Dim sMyWord as String

Dim iMyNumber as Integer

    sMyWord = Range("A1").Text

    iMyNumber = Range("A1").Value

End Sub

To assign an Object to an Object type variable you must use the key word "Set". eg:

Sub SetObJect()

Dim rMyCell as Range

    Set rMyCell = Range("A1")

End Sub

In the example immediately above, we have set the Object variable to the range A1.  So when we have finished using the Object Variable "rMyCell" it is a good idea to Set it back to it's default value of Nothing.  eg:

Sub SetObjectBack()

Dim rMyCell as Range

    Set rMyCell = Range("A1")


    Set rMyCell = Nothing 

End Sub

This will mean Excel will not be reserving unnecessary memory.

In the first example above (Sub ParseValue()) we used 2 lines to declare our 2 variables ie
Dim sMyWord as String
Dim iMyNumber as Integer
We can, if we wish just use:
Dim sMyWord as String, iMyNumber as Integer
There is no big advantage to this, but you may find it easier.

Not Declaring Variables

There is a difference between using variables and correctly declaring them. You can if you wish not declare a variable and still use it to store a Value or Object. Unfortunately this comes at a price though! If you are using variables which have not been dimensioned Excel (by default) will store them as the Variant data type. This means that Excel will need to decide each time it (the variable) is assigned a value what data type is should be. The price for this is slower running of code! My advise is do it right and form the good habit early!

There is also another advantage to correctly declaring variables and that is Excel will constantly check to ensure you have spelt the variable name correctly. It does this by capitalizing the all lower case letters that are capitalized at the point it was dimensioned. Let's assume you you use:

Dim iMyNumber As Integer

At the top of your procedure. You then intend to use this variable in other parts of the procedure. Each time you type imynumber and then push the Space bar or Enter Excel will capitalize it for you i.e imynumber will become iMyNumber. This is a very simple and easy way to ensure you have used the correct spelling.

While we are on this subject, it is very good practice to type all code in lower case, because not only will Excel do this for variables but also for all Keywords!

There may be times when you will actually need to use a Variant data type as you cannot be certain what will be parsed to it, say from a cell. It might be text, it maybe a very low or high number etc. In these circumstances you can use:

Dim vUnKnown As Variant
Or, simply:
Dim vUnKnown

Both are quite valid! The reason we do not have to explicitly declare a Variant is because the default for a variable is a Variant.

See Also: Lifetime and Scope of Variables

Excel Dashboard Reports & Excel Dashboard Charts 50% Off Become an ExcelUser Affiliate & Earn Money

Special! Free Choice of Complete Excel Training Course OR Excel Add-ins Collection on all purchases totaling over $64.00. ALL purchases totaling over $150.00 gets you BOTH! Purchases MUST be made via this site. Send payment proof to [email protected] 31 days after purchase date.

Instant Download and Money Back Guarantee on Most Software


Excel Trader Package Technical Analysis in Excel With $139.00 of FREE software!

Microsoft � and Microsoft Excel � are registered trademarks of Microsoft Corporation. OzGrid is in no way associated with Microsoft

Some of our more popular products are below...
Convert Excel Spreadsheets To Webpages | Trading In Excel | Construction Estimators | Finance Templates & Add-ins Bundle | Code-VBA | Smart-VBA | Print-VBA | Excel Data Manipulation & Analysis | Convert MS Office Applications To...... | Analyzer Excel | Downloader Excel | MSSQL Migration Toolkit | Monte Carlo Add-in | Excel Costing Templates