Programming Microsoft Outlook and Microsoft Exchange, Second Edition (DV-MPS Programming)
VBScript should be familiar to any developer who has experience with Visual Basic or Visual Basic for Applications (VBA) because VBScript is a subset of them. Version 3.1 of VBScript, which includes many enhancements from previous versions, ships with Outlook 98. 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.
NOTE
For more information on the different versions and features of the VBScript language, visit http://msdn.microsoft.com/scripting.
Working with Variables
Variables in VBScript correspond to locations in memory where you can store information while your application is running. Variable names are easily identifiable words or phrases such as myColor, myObject, and myTotal. There are some restrictions on the naming of variables inside of the VBScript environment, including 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. (Scope will be discussed shortly.)
Declaring Variables
To make variables available to your application, you need to either explicitly declare the variable or have the VBScript language implicitly declare the variable for you. The easiest way to declare a new variable is to use the Dim statement inside your VBScript code. For example, to declare three new variables, you could write either of the following code fragments.
'Declaring variables using separate lines Dim myColor Dim myObject Dim Total 'Or you can use the same line and separate the names by 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 are likely to 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. The Option Explicit statement forces all VBScript variables to be explicitly declared. If you do not declare all your variables, VBScript will display an error. The Option Explicit statement must appear before any procedures and is typically the first statement in your code.
Scope and Lifetime of a Variable
The lifetime of a variable is determined by the scope in which the variable was declared. There are two levels of scope for a variable inside VBScript:
- Global, or script-level scope
- Local, or procedure-level scope
Global variables can be called from any procedure inside the running script. To create global variables, all you need to do is declare your variables outside any procedure in your script. It is best to group all global variables at the top of your script instead of smattering 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 these variables from other procedures, VBScript displays an error. Also, procedure-level variables in different procedures can have the same name.
The next code snippet shows both script-level and procedure-level variables being declared. To test this code, 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. The CommandButton control will be named CommandButton1 automatically. Display the Script Editor by selecting View Code from the Form menu. Type the following code in the Script Editor. When finished, 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 Dim our variables before using them Option Explicit 'Global/script-level variables Dim strName strName = "Joe User" Sub CommandButton1_Click Dim strLocation 'Procedure-level variable strLocation = "Seattle, Washington" msgbox strName & " is located in " & strLocation End Sub |
The length of time a variable exists is called its lifetime. 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, that variable will be created when the procedure begins and destroyed when the procedure ends. This is why procedure-level variables are good 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.
The following code snippet demonstrates variable lifetimes:
'Make sure to Dim our variables before using them Option Explicit 'Global/script-level variables Dim strName strName = "Joe User" Sub CommandButton1_Click Dim strLocation 'Procedure-level variable 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. You will receive a "Variable is undefined" error message from Outlook because the variable strtLocation is a procedure-level variable, and it is destroyed after the CommandButton1_Click procedure is complete.
Data Types in VBScript
If you're a Visual Basic or VBA programmer, you've probably been wondering how in VBScript you can explicitly declare variables as different data types. Well, the answer is you can't because VBScript supports only one data type, Variant. The Variant 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—for example, if you place a number in a VBScript variable, VBScript assumes the subtype should be numeric and treats it as a number.
By using the built-in conversion functions of VBScript, you can turn any variable into different subtypes. For example, with 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.
Working with Objects
You work with objects in VBScript in the same way you work with variables except for one difference: when working 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 illustrate why, consider the previous code example in which you set the strtName variable to the string Joe User by using the following statement:
strName = "Joe User" |
For an object, the syntax would be 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 first need to 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, properties and methods can be accessed with 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 |
Early Binding vs. Late Binding in VBScript Code
Binding is a term that describes the association of a variable with an object. In Visual Basic, there are basically two times in which this binding can occur, compile time and run time. The 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, has the advantage of being flexible 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 does make it slower than early binding. Since all variables in VBScript are declared as Variant data types, you cannot take advantage of early binding in your code. Instead, VBScript uses late binding.
Constants in VBScript
When using VBScript in Outlook, you sometimes must refer to predefined constants, such as olMailItem. You can't use the constant by name, but rather you must use the constant's numeric value. For example, if you wanted to use the constant olMailItem in your code, you would need to 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 look up a particular constant in the Outlook Object Browser. The Outlook Object Browser is discussed later in this chapter.
Error Handling
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 since it returns messages that are not properly formatted for the user—they're really more for the developer. To override the default error handler, you need to follow two steps in your VBScript code.
First you need to tell VBScript how to proceed when an error occurs. By default, all run-time errors in VBScript are considered fatal errors. This means that an error message will appear and the script will stop running. To override the built-in error message in your VBScript 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 the error. VBScript provides a global object, the Err object, which has properties you can check to get information about an error. These properties include a number that identifies the error and descriptive text about the error. Typically, you would check the error number property to see whether it is a number besides 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 once 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 any of the following three statements: On Error Resume Next, Exit Sub, or Exit Function. 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 |
In 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, 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.