Variables
Naming Variables
Variables follow the same naming convention as Subroutines:
Must be less than 255 characters
Use only letters, numbers or underscores
No spaces allowed (either use CamelCase or use_underscores)
Cannot begin with a number
There is a notation (though unofficial) called the Leszynski, or Hungarian notation, that suggests
prefixing names of variables, objects etc. with an abbreviation of what they are:
intMyCounter As Integer int indicating this is type Integer
frmMyForm frm indicating this is a form
ModTheBasics Mod indicating this is a Module
More here: https://en.wikipedia.org/wiki/Leszynski_naming_convention
The Scope of a Variable
Scope simply means where can you see it. The scope of a variable is determined when you declare
it:
Procedure Level Can be used only in the Sub it‘s declared in* Declared with Dim
Module Level Can be used anywhere in the current module. Declared with Dim
Project Level Can be used anywhere in the current project. Declared with Public
*Can be passed to another sub if the code is modified (see lecture Variables - Local Variables With A
Twist)
The Lifetime of a Variable
Local Dim Destroyed at End Sub of the Sub in which it was declared, or End statement
Module Dim Destroyed at:
Workbook Close
"Stop" is hit in the VBE
A new Sub is added to the Module
End statement
Proc Public Destroyed at End Sub of the module in which it was declared, or "End"
statement
Assigning a Value to a Variable
Before a Variable is useful, we need to put something in it!
Hard Coded strMyString = “Hello World”
Dynamically coded strMyString = Range(“A1”).Value
Data Types of Variables
Type Description Memory allocated
Boolean TRUE or FALSE 2 bytes
Integer A whole number between -32768 and 32767 2 bytes
Long 2,147,483,648 to 2,147,483,647 4 bytes
Single -3.4028235E+38 through -1.401298E-45 † for negative 4 bytes
values;
1.401298E-45 through 3.4028235E+38 † for positive
values
Double -1.79769313486232E308 to -4.94065645841247E-324 8 bytes
for negative values;
4.94065645841247E-324 to 1.79769313486232E308
for positive values
Currency -922,337,203,685,477.5808 to 8 bytes
922,337,203,685,477.5807
Date January 1, 100 to December 31, 9999 8 bytes
String Text 10 bytes + string length
Variant Anything at all >16 bytes
Syntax for Declaring a Variable
Dim X As Integer Can be used Locally (in Sub), or Module level (Declarations Section)
Public Y As Long Used at Project level (in the Declarations Area)
You can declare multiple variables on the same line:
Dim X As Integer, Y As Long (All must be Dim in this instance)
Public X As Integer, Y As Long (All must be Public in this instance)
For more information, see the Microsoft article below:
https://support.microsoft.com/en-gb/kb/843144