2.1 The Concept of Variables in Excel VBA
A variable is like a mailbox in the post office as its content changes every now and then, just like the mailboxes. In Excel VBA, variables are areas allocated by the computer memory to hold data. Similar to the mailbox, each variable must be given a name. In order to name a variable in Excel VBA, you have to follow a set of rules, as follows:
- It must be less than 255 characters
- No spacing is allowed
- It must not begin with a number
- Period is not permitted
Examples of valid and invalid variable names are displayed in Table 2.1
2.2 Declaring Variables
In Excel VBA, you need to declare the variables before using them by assigning names and data types. We can divide the Excel VBA data types into two types, the numeric data types and the non-numeric data types
2.2.1 Numeric Data Types
Numeric data types are types of data that consist of numbers. We can compute the numeric data mathematically with various standard operators such as plus, subtract, multiply, divide and so on. In Excel VBA, we can divide the numeric data into 7 types, as shown in Table 2.2
2.2.2 Non-numeric Data Types
We can declare the variables implicitly or explicitly. For example, sum=text1.text means that the variable sum is declared implicitly and ready to receive the input in the Text1 textbox. In addition, other examples of the implicit declaration are volume=8 and label=”Welcome”. On the other hand, for the explicit declaration, we declare the variables in the general section of the code window by using the Dim statement. The syntax is as follows:
Dim variableName as DataType
Dim password As String Dim yourName As String Dim firstnum As Integer Dim secondnum As Integer Dim total As Integer Dim BirthDay As Date
On the other hand, you may combine them in one line, separating each variable with a comma, as follows:
Dim password As String, yourName As String, firstnum As Integer.
If the data type is not specified, Excel VBA will automatically declare the variable as a Variant. For string declaration, there are two possible formats, one for the variable-length string and another for the fixed-length string. For the variable-length string, just use the same format as Example 2.1 above. However, for the fixed-length string, you have to use the format as shown below:
Dim VariableName as String * n
where n defines the number of characters the string can hold. For example, Dim yourName as String * 10 mean yourName can hold no more than 10 Characters.
In this example, we declared three types of variables, namely the string, date and currency.
Private Sub CommandButton1_Click() Dim YourName As String Dim BirthDay As Date Dim Income As Currency YourName = "Alex" BirthDay = "1 April 1980" Income = 1000 Range("A1") = YourName Range("A2") = BirthDay Range("A3") = Income End Sub
The output screen of Example 2.2 is as follows: