VBScript should be familiar to any developer who has experience with Microsoft Visual Basic or Microsoft Visual Basic for Applications (VBA) because VBScript is a subset of those languages. Version 5.6 of VBScript, which includes many enhancements over previous versions, ships with Outlook. As you would expect, you write VBScript applications in the same way you write applications in other programming languages ”by using variables , procedures, and objects.
Variables in VBScript correspond to locations in memory where you can store information while your application is running. Variable names consist of easily identifiable words or phrases, as in myColor , myObject , and myTotal . You are restricted in how you can name variables in the VBScript environment, however. The restrictions include the following:
The variable name must begin with an alphabetic character. For example, myTotal is a legal variable name, but $Total is not.
The variable name cannot contain an embedded period. For example, this.total is not a valid variable name.
The variable name cannot contain more than 255 characters .
The variable name must be in a unique scope when declared. (We'll discuss scope shortly.)
To make a variable available to your application, you must either explicitly declare it or have the VBScript language implicitly declare it for you. The easiest way to declare a new variable is to use the Dim statement in your VBScript code. For example, to declare three new variables, you can write either of the following code fragments :
'Declaring variables using separate lines Dim myColor Dim myObject Dim Total 'Declaring variables on one line, separating the names with commas Dim myColor, myObject, Total
VBScript does not require you to explicitly declare variables. If you do not declare a variable and you use that variable in your code, VBScript will automatically save storage space for your data and use your variable as the friendly name for that storage space. However, if you accidentally misspell a variable in your code, errors will likely occur in your application. These errors are particularly hard to track down because the VBScript interpreter does not know that a variable has been misspelled . To make these types of errors more manageable, VBScript provides the Option Explicit statement. If you use this statement, you must explicitly declare all VBScript variables or VBScript will display an error. The Option Explicit statement must appear before any procedures and is typically the first statement in your code.
A variable's lifetime ”how long it exists ”is determined by the scope in which the variable is declared. A variable can have one of two levels of scope in VBScript: global (script-level) scope or local (procedure-level) scope.
Global variables can be called from any procedure within the running script. To create a global variable, you simply declare that variable outside any procedure in your script. It is best to group all global variables at the top of your script instead of scattering them throughout your code.
Local variables are declared within procedures and can be accessed only by the code in that procedure. If you attempt to call one of these variables from other procedures, VBScript will display an error. Also, procedure-level variables in different procedures can have the same name.
The next code snippet shows declarations for both script-level and procedure-level variables. You first create a new Message form in Outlook and enter design mode. Drag and drop a CommandButton control onto the second tab of the Outlook form. This control is automatically named CommandButton1. Display the Script Editor by choosing View Code from the Form menu. Type the following code in the Script Editor. When you finish, try running the form by choosing Run This Form from the Form menu and then clicking the button on the second tab.
'Make sure to enforce variable declarations Option Explicit 'Global/script-level variables Dim strName strName = "Joe User" Sub CommandButton1_Click 'Procedure-level variable Dim strLocation strLocation = "Seattle, Washington" MsgBox strName & " is located in " & strLocation End Sub
The scope in which the variable is declared affects the lifetime of the variable. For example, if a variable is declared with script-level scope, it will exist the entire time the script is running. If the variable is declared with procedure-level scope, it will be created when the procedure begins and destroyed when the procedure ends. This is why procedure-level variables are useful as temporary storage space inside your VBScript procedures. Some restrictions apply to VBScript variables and their lifetimes:
You can have up to 127 procedure-level variables. Arrays count as only one variable.
You can have up to 127 script-level variables.
To demonstrate variable lifetime, let's add a second CommandButton (automatically named CommandButton2) to the form and modify the script to look like the following:
'Make sure to enforce variable declarations Option Explicit 'Global/script-level variables Dim strName strName = "Joe User" Sub CommandButton1_Click 'Procedure-level variable Dim strLocation strLocation = "Seattle, Washington" MsgBox strName & " is located in " & strLocation End Sub Sub CommandButton2_Click 'Attempt to use variable from the previous procedure MsgBox strLocation End Sub
When you run this code, click CommandButton1 and then click CommandButton2. If you do not have JIT debugging enabled, you will receive a "Variable is undefined : strLocation" error message from Outlook because the variable strLocation is a procedure-level variable and is destroyed after the CommandButton1_Click procedure is complete.
If you're a Visual Basic or VBA programmer, you've probably been wondering how to explicitly declare variables as different data types in VBScript. Well, you can't because VBScript supports only one data type, Variant . This data type is special in that it can hold many categories of information, such as text, numbers, dates, times, floating-point numbers , and objects. These categories of the Variant data type are called subtypes . The Variant data type works in such a way that VBScript can figure out what subtype to use based on the information the variable holds; for example, if you place a number in a VBScript variable, VBScript will assume that the subtype is numeric and will treat it as a number.
By using the built-in conversion functions of VBScript, you can turn any variable into a different subtype. For example, by using the CStr function, you can convert an expression into a string. By using the VarType function, you can obtain the current subtype for a variable.
You work with objects in VBScript in the same way you work with variables, but with one difference: when you work with objects, you use the Set statement to set the variable to point to the object. When you work with variables, you do not use the Set statement. To see why, consider the previous code example in which we set the strName variable to the string " Joe User" by using the following statement:
strName = "Joe User"
For an object, the syntax is different. Let's look at an example in which a hypothetical object named Information has a property named UserName . To access this object in VBScript, you must first set a variable to the object and then use the dot (.) operator to access the specific object property. You can also use the dot operator to access a specific method on the object. Following is a code snippet that shows the variable myInformation being set to the Information object. Using the myInformation variable, you can access properties and methods by using the dot notation.
'The variable that will hold the Information object Dim myInformation 'Set a variable to the Information object Set myInformation = Information 'Initialize the UserName property of the Information object myInformation.UserName = "Michael Dunn" 'Get the UserName property of the Information object msgbox "Current User is " & myInformation.UserName 'Call the Print method of the Information object myInformation.Print
Binding describes the association of a variable with an object. In Visual Basic, binding for a particular variable can occur at compile time or at run time. Binding that occurs at compile time is called early binding . The advantage of early binding is that the compiler can perform some data-type and function-name checking. Binding at run time, or late binding, provides flexibility because the object does not have to be explicitly specified at compile time. The disadvantage of late binding, however, is that it requires additional code, which makes it slower than early binding. Because all variables in VBScript are declared as Variant data types, you cannot take advantage of early binding in your code. VBScript uses only late binding.
When you use VBScript in Outlook, you must sometimes refer to predefined constants, such as olMailItem . You can't use the constant by name; instead, you must use its numeric value. For example, if you want to use the constant olMailItem in your code, you must use the value 0. VBScript does support user-defined constants and some intrinsic constants, but if the constants are defined in another file, you must either use the constant's numeric value or explicitly declare the constants in your code. You can find a list of all the constants and their values in the Outlook help file, or you can look up a particular constant in the Outlook Object Browser. The Object Browser is discussed later in this chapter.
The VBScript engine provides very basic error-handling functionality. For example, if a run-time error occurs, VBScript will display a message and stop execution. You'll probably want to override the default error handler because it returns messages that are not properly formatted for the user ”they're really more for the developer. To override it, you must perform two steps in your VBScript code.
First you tell VBScript how to proceed when an error occurs. By default, all run-time errors in VBScript are considered fatal errors, which means that an error message appears and the script stops running. To override the built-in error message in your code, add the On Error Resume Next statement in each procedure in which you want custom error handling. This statement informs VBScript to continue executing, beginning at the line following the code that caused the error.
Second you need to figure out what the error was and what the application should do about it. VBScript provides a global object, Err , that has properties you can check to get information about the error. These properties include a number that identifies the error and descriptive text about the error. Typically, you check the error number property to see whether it is a number other than 0. If the property is 0, no error has occurred. The following code shows how to check the error number using VBScript:
If Err.Number <> 0 Then 'Put your error-handling code here, and exit the procedure Exit Sub End if
VBScript lets you clear the Err object after an error has been raised so that other error-handling routines in your application do not reprocess the error. VBScript also automatically clears the Err object for you after it encounters the On Error Resume Next , Exit Sub , or Exit Function statement. The following code snippet demonstrates how to display more detailed error messages by using the properties of the Err object:
Dim strMessage strMessage = "The following error, " & Err.Description & _ ", has occurred in the " & Err.Source & " application. " & _ "The error number was " & Err.Number & ". " & _ "Please report this error to the help desk." MsgBox strMessage, 16, "Run-time Error #" & Err.Number
When determining what action to take in your error-handling code, you should consider whether to exit the procedure or just continue executing the code in the procedure. If the error is nonfatal, you should display a dialog box to inform the user of the error and continue executing. If the error is fatal, gracefully exit the procedure and continue the application if possible.