When you want to use a variable in programming, you should declare it.
In VBA, declaring has two steps:
- Set a name for the variable. For example, you might call yours “quarterlySales.”
- Set a type for the variable. We’ll go over types in more detail in the next section. For now, just think of type as telling Excel what sort of data you’re going to store in that variable.
For example, you might store a number, a date, or a string of text. You have to tell Excel what kind of data is going to be stored in the variable before you start using it.
Let’s take a look at an example in VBA. We’re going to create a variable called “firstName” and tell Excel that it will contain a string of text. Here’s the syntax we’ll use:
Dim firstName As String
Let’s go over that one step at a time.
First, we have “Sub getNames()”. This is the beginning of a VBA procedure. You’ll often declare new variables inside of procedures.
Then we come to “Dim firstName As String.”
Dim is short for “Dimension,” and it’s what you use to declare a new variable. Dim tells Excel that the next thing we type is the variable name. In this case, that’s “firstName.”
After that, we have “As.” You always need “As” in your declaration statement—it tells Excel that you’re going to use the following data type for that variable.
So in our case, we’re saying “I’m going to use a variable called firstName, and it’s going to contain Strings.”
Finally, we have “End Sub,” which tells Excel we’re done working on this procedure.