In VBScript, as with any programming language, it is extremely important to familiarize yourself with variables and how they work. Variable usage in VBScript is highly simplified, but before we begin, let’s take a look at what variables are exactly.
Much like their mathematical cousins, in programming, variables are used to reference some piece of data. In programming, that data is stored in memory and a variable serves as a reference to the memory address where the data is located.
As their name implies, variables are dynamic. Values can be assigned and reassigned at any time throughout their lifespan. Unlike some other programming languages, variables in VBScript do not need to have a value assigned to them when they are initialized, although this is a common practice.
Understand the difference between variables and constants: the value of a variable can be changed while the value of a constant cannot be changed once it has been initialized.
You should also be aware of data types. As with any programming language, multiple data types exist, however, all variables are of type Variant. This means that you do not need to declare a data type when initializing a variable and that you may change the data type associated with it at any time.
This comes as both a blessing and a curse. On one hand, you can perform data type conversions on the fly, which can prevent a lot of runtime errors. On the other hand, these “behind the scenes” conversions can often produce some pretty unexpected results.
The naming conventions in VBScript are pretty straightforward. Variable names may not be longer than 256 characters and may not contain spaces. They must consist only of alphanumeric characters and underscores. The first character in a variable name cannot be a number.
Unlike JavaScript, variable names in VBScript are case insensitive. Their name should be representative of the data that they contain. For instance, if you have a variable that represents a client’s name, you would be better off naming it "clientname," rather than something obscure like "n1." It’s also good practice to use the recommended naming conventions, although it is not required by the interpreter.
According to the naming conventions, a variable name should begin with an abbreviation that represents the intended data type for its value. Parts of the name should also be capitalized for readability. Following the naming conventions, the variable in the last example should be named "strClientName," since it most likely would reference a string containing a client’s name. The table below lists the data subtypes in VBScript along with their abbreviations.
Subtype
Abbr
Example
Boolean
bln
blnFound
Byte
byt
bytRasterData
Date (Time)
dtm
dtmStart
Double
dbl
dblTolerance
Error
err
errOrderNum
Integer
int
intQuantity
Long
lng
lngDistance
Object
obj
objCurrent
Single
sng
sngAverage
String
str
strFirstName
While this isn’t part of the official naming conventions, another common practice is to name object variables with prefixes that are indicative of the object’s type. The table below shows a list of common prefixes that I often use in my code examples.
Object Type
Abbr
Example
Array
arr
arrNames
Collection
col
colItems
Dictionary
dict
dictStateAbbr
External Object
obj
objFso
According to the naming conventions, variables should also be named according to their scope. A variable’s scope is the area within a script or program from which the variable may be safely referenced. This is determined by where the variable is initialized.
A variable’s scope may be either procedure-level or script-level (sometimes referred to as global). A procedure level variable is initialized within a procedure, such as a function, subroutine, or event. Script-level variables may be initialized anywhere outside of a procedure.
Attempting to reference a variable outside of its scope will result in a runtime error.
The naming conventions suggest adding an "s" prefix to any script-level variable. Procedure-level variables do not change. I’ve provided a simple example below.
sstrScriptLevel = "A script level variable."
'The following line results in a runtime error because the variable
'is out of scope.
WScript.Echo strProcedureLevel
Sub MySub
strProcedureLevel = "A procedure level variable."
' The following line is completely valid.
WScript.Echo sstrScriptLevel
End Sub
By now you may be wondering why you should bother with the naming conventions at all, if they’re not required by the interpreter. The naming conventions were developed as a way to help multiple programmers working on the same project, or to help a single developer with a large project.
By using naming conventions, you can tell at a glance what data type a variable will provide and what its scope is. This is especially useful if you are reworking someone else’s code or updating code you may have written in the past.
Now that you’ve seen what variables are and how to name them, it’s time to begin putting them to use in your own scripts. To do that, you first need to learn how to declare, or create them.
There are two terms that you will hear used when talking about variables. You should become familiar with their proper definitions. Declaring a variable means creating its reference in memory. This makes it available for use. Initializing a variable means assigning its first value. In VBScript, variables are often declared and initialized at the same time.
The proper method for declaring a variable in VBScript is to use the Dim statement. The Dim statement allocates memory for the variable.
Dim intNumber
You declare any number of variables in a single statement by separating them with commas.
Dim strName, strAddress, strCity, strState, intZipCode
In VBScript, you do not need to declare the type associated with the variable as you would in VisualBasic.
Dim intNumber As Integer
The use of the As statement in VBScript will result in an "Expected end of statement" error, since the As keyword is not recognized.
Explicit declarations allow you to control the scope of your variables more effectively.
VBScript will automatically create any variable found in an expression. There may be times when you don’t want this to happen. Imagine that you are trying to debug a script where you mistyped a variable name. Your script will most likely not perform as you intended it to, but in most cases, it won’t throw any errors either. Forcing VBScript to only use explicitly declared variables can help you avoid this scenario.
Option Explicit:
Using the Option Explicit statement at the beginning of your script will force the VBScript interpreter to throw an error any time it encounters a variable that was not explicitly declared. In other words, it forces the use of the Dim statement.
As I mentioned previously, there are multiple data types in VBScript. They can be divided into two major categories: numeric and non-numeric. As their name implies, numeric variables are variables whose value is recognized as a number. Non-numeric types are the opposite and include strings, Booleans, and empty variables among others.
You can determine a variable’s data subtype by using VBScript’s VarType or TypeName function. The table below lists the return values for the VarType function and also serves as a list of the available data subtypes in VBScript.
Constant
Value
Description
vbEmpty
0
Empty (uninitialized)
vbNull
1
Null (no valid data)
vbInteger
2
Integer
vbLong
3
Long integer
vbSingle
4
Single-precision floating-point number
vbDouble
5
Double-precision floating-point number
vbCurrency
6
Currency
vbDate
7
Date
vbString
8
String
vbObject
9
Automation object
vbError
10
Error
vbBoolean
11
Boolean
vbVariant
12
Variant (used only with arrays of Variants)
vbDataObject
13
A data-access object
vbByte
17
Byte
vbArray
8192
Array
The TypeName function works similarly, but instead it returns the variable type as a string. You can see an example of both in the example below.
VBScript provides a number of other functions that can be used to determine the type and state of your variables. These functions return Boolean values according to the table below.
IsArray
Returns True if a variable references an array.
IsDate
Returns True if a value is a date or can be converted to a date.
IsEmpty
Returns True if a variable is uninitialized.
IsNull
Returns True if a variable is initialized but does not contain valid data.
IsNumeric
Returns True if a variable’s value can be interpreted as a number.
IsObject
Returns True if a variable represents an object.
This article is designed to be an introduction to using variables in VBScript. At this point, you should be able to create and implement variables in VBScript, and also be aware of their types and states. In future articles, I will demonstrate how to work with specific data types as well as how to convert between them.