Declaring Variables
- 02:37
How to declare and use variables in Excel VBA.
Downloads
No associated resources to download.
Transcript
When using variables in VBA code, it's good practice to declare the variables used in our code.
It's also good practice to declare the variables as locally as possible.
DIM is used to declare the variable.
If the variable is declared within a sub procedure, it's local to that sub or sub procedure, ie.
The variable is only known by that sub procedure.
If the variable is declared as public, it is known to all subs in all modules in the workbook.
In the first example, variable X is assigned a value of 50 and variable Y is assigned a value of 57.
The next line of code uses excel VBA function message box.
We would expect a message box to appear stating the product of 50 and 57.
This code would've worked if it were not for the option explicit statement at the top of the module.
Option explicit requires all variables to be declared.
This is good practice.
It helps our code run smoothly and allows others to follow our code more readily.
The next sub procedure demonstrates much better.
excel VBA coding practice variables are declared as integers using the dim syntax.
This means that the variables can take any whole number between plus 32,000 and minus 32,000.
Notice the variable name is a mixture of uppercase and lowercase letters so that it can easily be differentiated from other coding instructions.
If we type Y input into our code, VBA recognizes the variable name and we'll convert this into Y input with a lowercase Y and an uppercase I for input.
This is really helpful, especially if we have made a mistake.
What spelling? When typing our variable name, the variables are then assigned a value.
And finally, the excel VBA message box function will display a message box stating the product of 50 and 60 to display 3000.