VBScript is different from many other programming languages in that it doesn't need to have variables defined as specific types - instead it used a variable type called a variant. A variant can contain any data type. That's not to say that the data type doesn't change - what actually happens is that VBScript changes the data type for the programmer automatically. So that raises the question - how does a programmer work with Variables in VBScipt?
Defining a Variable in VBScript
Variables can be created with VBScript just by assigning a value to the variable, for example:
However, this is not considered good practice because errors can easily creep in without the programmer being aware of them:
A much better solution is to force variable declaration by using the option explicit statement:
Notice that the variable is defined without a data type, but the important point is that the following will now cause an error:
Next the programmer can start thinking about the data types of the variables.
Identifying the VBScript Variable Types
Having said that the variables are all the same data type (variant), the data type does change as soon as a value is assigned to the variable, and the data type of a variable can be examined by using either of two VBScript methods:
- TypeName - returns the name of the data type
- VarType - returns the VBScript number representing the data type
For example:
In fact, the data type can change continually through the running of the script:
Having seen that the data types do change it's worth looking at what those data types are.
The VBScript Variable Types
There are 16 data types used by VBScript and each is identified by:
- a VBScript constant (shown by using VarType)
- a name (shown by using TypeName)
It should be noted that the numbering for the VBScript constants is not consecutive:
Each of the constant values can be used by prefixing the data type name with vb, for example:
However, even though VBScript assigns all of the data type, it is still possible for the programmer to change them.
Manually Changing the Data Types
VBScript will change the data type automatically as the script progresses; however, the programmer can manually change the data type if required. The conversion methods, and the data type that they convert to, are:
So, for example:
And so the programmer has the choice to control the variable data types or to let VBScript do all of the hard work.
Summary
Variables in VBScript are very liberal - they allow programmers to create variables with the data type variant and will the automatically assign the correct data type when a value is assigned to the variable; this data type can be queried by using either of two methods:
- TypeName
- VarType
Of course once the data type has been assigned the programmer can manually change it if the script required it.