Specifying Variable Data Type

When you declare a variable, you can also supply a data type for it. The data type specifies the kind of information you can store in the variable. If you don't supply a data type, Visual Basic automatically gives the variable the Variant data type.

The Variant data type handles all types of fundamental data and converts between them automatically. If you want to create concise, fast macros, however, use other data types whenever you know that a variable will always contain the same type of data. For example, if a variable always contains small integer values, you can save several bytes (and speed up your macro significantly when performing arithmetic operations on the variable) by declaring that variable as Integer instead of Variant. For information about specific data types, see "Data Types" later in this chapter.

Before you can use a non-variant variable, you must explicitly declare it using the As keyword in a declaration statement. For example, the following statements declare variables as Long, Integer, Double, String, and Currency, respectively.


Dim x as Long
Private i As Integer
Private amt As Double
Static yourName As String
Public billsPaid As Currency

A declaration statement can combine multiple type declarations, separated by commas, as in the following statements.


Private i As Integer, amt As Double
Private yourName As String, billsPaid As Currency
Private test, amount, j As Integer    ' test and amount are Variants

Note

If you don't specify a data type for a variable, Visual Basic assigns the Variant data type. In the preceding example, the variables test and amount have the Variant data type. This may surprise you if your experience with other programming languages leads you to expect all the variables in one declaration statement to have the same specified data type (in this case, Integer).