Day 3 VBA Hero – Defining Variables.


Someone once told me that to understand any programming language, you need to understand three points: variables, loops and arrays.

This lesson will explain the first point.

A variable is something that is used to store information in it, to be used later on in your code.

For example, if you need to copy today’s date in multiple places in your document, you could create a variable which would store today’s date.

Thus, everytime you would need to insert today’s date, you would use the variable.

It also make it easier to modify one variable that is referred to multiple times that multiple changes in the same code.

A practice that many use is to declare a variable at the top of your code.

To declare a variable, you need to add the word “Dim” before the name of the variable that you wish to use.

For example: Dim todaysDate

To conserve memory and as a good practice, it is all best to define what will be in the variable, in the above case, you could say “Date”

So, you would write

Dim todaysDate as Date

There are of course many different variable types, far too many to even name. I have noticed with the operations that I use in Excel, I use only a handful.

String: Information stored as text. All text is considering string.

Integer: Information stored as a whole number between – 32 767 and 32 767. If you would store 23.56 in a variable that you have declared as an integer, it would return the value 24 (rounds to nearest whole number).

Long: Information stored a longer integer. When you need a larger range than what an integer can offer, this is your solution.

Double: Information stored as a number with decimal places, without the limit of an integer.

Range: Information stored as a cell or group of cells in Excel.

Object: Information stored as a worksheet or workbook.

Date: Information stored in date format.

Variant: when no type of variable is declared, this is the default.
I may add some more, but with these 8 different variable types, you should be able to do whatever you need.

Verified by MonsterInsights