Downloads
6125.zip

Behind almost any scripting operation or program, an operator and a statement are at work. Operators perform arithmetic, comparison, logical, and concatenation operations. Statements provide elementary computing capabilities, such as decision-making, repetition, and assignment. Together, statements and operators let you perform fundamental operations and build blocks of more complex code (i.e., functions and procedures). Last month, I discussed VBScript's operators. This month, I cover some of VBScript's statements.

VBScript contains six types of statements: declaration statements, conditional statements for decision-making, loop statements for repetition, errorhandling statements, classes, and subroutines. I covered declaration statements (i.e., Dim, ReDim, and Option Explicit) in my June column, and I'll discuss classes and subroutines in future issues. In this column, I discuss conditional and loop statements, with a look at error-handling constructs. But before I jump into this discussion, you need to understand the difference between a statement and a function.

Statements vs. Functions
People often confuse statements and functions, but their purposes are quite different. A statement performs an elementary action that affects the flow of the script. A function is a block of instructions that affects the data the script is handling. The block of instructions can include statements, built-in functions (i.e., functions that VBScript provides), and user-defined functions (i.e., functions that users create). A statement can't include a function.

Another important difference concerns return values. A function returns a value, but a statement doesn't.

Conditional Statements
A conditional statement is a point at which the script decides whether to execute the next instruction (i.e., a statement or set of statements). A logical condition (i.e., an expression that evaluates to True or False) guides this decision.

The simplest conditional statement is the If...Then...Else statement. In a script, this statement takes the form

If condition Then
  \[statements\]
Else
  \[Else statements\]
End If

In this syntax, there are two main branches: If...Then and Else. The If...Then branch defines what to do if the condition is True. The Else branch defines what to do if the condition is False. For example, consider the conditional statement

If A > B Then
  Result = True
Else
  Result = False
End If

This code is telling the system to set the Result variable to True if A > B; otherwise, set the Result variable to False. This example illustrates an important aspect of the If...Then...Else statement: The two branches are mutually exclusive.

A good programming practice is to put the most likely alternative in the If...Then branch and reserve the Else branch for the less likely alternative. Programmers initially developed this practice as an optimization technique for compiled languages. Although VBScript is an interpreted rather than a compiled language, this practice is a sound one, even though it doesn't produce noticeable improvements in execution speed.

Using five lines of code for an If...Then...Else statement can make a script long and tedious. You can rewrite the code so that it's more compact and readable. For example, you can rewrite the previous If... Then...Else statement as

Result = False
If A > B Then Result = True

The effect is the same, but you saved three lines of code. This rewrite employs an underused feature of the If...Then...Else statement: the capability to support just one branch and writing that branch as all one line. If you use this one-line branch, don't use End If to terminate the statement. Although your code will still work, it's incorrect.

You can concatenate more statements to the one-line branch by adding a colon, followed by the additional statements. For example, if you want to display the result of the If...Then...Else statement, you can use the code

Result = False
If A > B Then Result = True:MsgBox _ Result

(The underscore after True:MsgBox specifies that the branch continues on the next line.) The long version of this code is

If A > B Then
  Result = True
  MsgBox Result
Else
  Result = False
End If

On the Win32 Scripting Journal Web site, the Web-exclusive sidebar "A VBScript IIf ( ) Function" demonstrates yet another approach to conditional statements: a user-defined VBScript function that simulates Visual Basic for Applications' (VBA's) IIf( ) function. Choosing between the various approaches is a matter of personal preference. If you're a VBScript novice, I suggest that you use the one-line branch if the system needs to follow only one instruction under a True condition. If there are several instructions, using the full If...Then...Else statement is preferable because it's easier to understand.

More Complex Conditional Statements
Up to this point, the If...Then...Else statements have had two branches (If...Then and Else) because you've had two options to choose from. When you have more than two options, you can add more branches, called ElseIf clauses, to the If...Then...Else statements. The ElseIf clause concatenates more If...Then branches and lets you consider each circumstance separately. With this clause, you can define multiple, nested If...Then branches that are still mutually exclusive. You can check a different condition at any level in the If...Then...Else statement. The syntax for the ElseIf clause is

If condition Then
  \[statements\]
\[ElseIf condition Then
  \[ElseIf statements\]\]
\[Else
  \[Else statements\]\]
End If

For example, suppose you have an important deadline coming up. You want to post a message on your PC reminding you about that deadline. If the deadline day hasn't arrived yet, you want the message to say that you have X more days (where X is the deadline date minus today's date). If the deadline day has arrived, you want the message to say that you're on time. If the deadline day is past, you want the message to say that you're X days late. As Listing 1 shows, you can use an ElseIf clause in an If...Then...Else statement.

You can add as many ElseIf clauses as you need. However, when you have many options, using the Select Case statement is preferable because of its simplicity.

The Select Case statement lets you compare an expression against several other expressions. The final but optional clause, Case Else, specifies the code to execute if no match occurs. This statement takes the form

Select Case test expression
\[Case expression list-1
  \[statements-1\]\]
\[Case expression list-2
  \[statements-2\]\]
\[Case Else
  \[Else statements\]\]
End Select

For example, the following Select Case statement compares the value that variable i holds against the values of 0 and 1:

Select Case i
Case 0
  MsgBox "It's 0"
Case 1
  MsgBox "It's 1"
Case Else
  MsgBox "No match"
End Select

ElseIf clauses and the Select Case statement are similar but not equivalent. You can use ElseIf clauses to simulate a Select Case statement, but you can't use a Select Case statement to simulate ElseIf clauses. Microsoft designed If...Then...Else statements for decisions that involve logical expressions. For example, Listing 1 contains the logical expression If today < theDate Then. Microsoft designed Select Case statements for decisions that involve exact matches. With Select Case statements, you can match numeric values.

Loop Statements
You can repeat, or loop, an instruction or block of instructions with four statements:

  • For...Next
  • For Each...Next
  • While...Wend
  • Do...Loop

The For...Next statement lets you execute an instruction a fixed number of times. You specify this number with a counter. The counter has a start point and an endpoint. The syntax is

For counter = start point To _
  endpoint
  \[statements\]
Next

For example, consider the code

For i = 0 To 10
  MsgBox i
Next

The counter, variable i, has the start point of 0 and the endpoint of 10, so it tells the system to execute the specified block of code 11 times. The start point and endpoint for the counter can be any integer. In each iteration, the counter increases by 1 unless you specify otherwise with the Step clause. The Step clause lets you set the range of increment to any number, including negative values. For example, the statement

For i = 10 To 30 Step 2
  MsgBox i
Next

tells the system to execute the code on 10, 12, 14, 16, and so on, until it reaches 30 for a total of 11 times. The statement

For i = 200 To 100 Step -2
  MsgBox i
Next

tells the system to execute the code on 200, 198, 196, and so on, until it counts down to 100.

In the For Each...Next statement, you don't specify how many times to execute an instruction but rather ask the system to walk through all the items of a collection or array and execute the instruction for any item that matches the criterion you specify. For example, suppose you want to walk through all the items in the arrList array and execute the specified code for any item that matches ItemX. To accomplish this task, you use the code

Dim ItemX
Dim arrList(10)
For Each ItemX In arrList
  MsgBox ItemX
Next

You can exit both the For...Each and the For Each...Next statements at any time by calling the Exit For command.

The While...Wend and Do...Loop statements execute an instruction only under a certain condition. The While...Wend statement executes an instruction as long as the conditional expression you specify is True. This statement takes the form

While condition
  \[statements\]
Wend

Wend is the keyword that specifies the end of the While loop. You can't break a While...Wend statement with an exit command, but you can break the loop by making the condition that governs the loop False. For example, you can set i to 10 to break the loop:

i = 0
While i < 10
  i = i + 1
Wend

The i = 0 instruction sets the i variable to 0 (i.e., initializes the i variable) before the loop starts so that you have full control over the loop. In a While...Wend statement, you typically need to initialize any variable that you use in a Boolean expression.

You can include additional code (e.g., an If...Then...Else loop) to While...Wend statements. The Web-exclusive sidebar "Reading the Name of the Display Adapter" contains a real-world example of a While...Wend statement with additional code. The sidebar discusses how to create VBScript code that reads the name of the display adapter from the system .ini file in the Windows 9x directory.

The Do...Loop statement is more structured than the While...Wend statement. The Do...Loop statement syntax is

Do \[\{While | Until\} condition\]
  \[statements\]
Loop

With this statement, you can execute an instruction while a certain condition is True or until it becomes True. You can also adopt the construct

Do
  \[statements\]
Loop \[\{While | Until\} condition\]

With this construct, you always execute the block of code at least once. The Do...Loop statement supports the Exit Do command, which provides a way for the loop to terminate.

You can find an example of the Do...Loop statement on the Microsoft Developer Network (MSDN) Web site. Go to http://msdn.microsoft.com/ scripting/default.htm?/scripting/vbscript/ techinfo/vbsdocs.htm. Click VBScript Tutorial. Select Looping Through Code under the VBScript Basics heading.

Error Handling Statements
The VBScript runtime automatically traps system errors that occur during code execution. When it traps an error, it stops the script's execution and displays an error message box. If you don't want an error to stop your script, you can place the statement

On Error Resume Next

at the top of a crucial instruction. This statement ensures that any error that occurs in statements from that point on won't be fatal. The system resolves the error by jumping to the next instruction. For example, suppose you have to create an object, but you don't know whether it exists on the client machine. If you put the code

On Error Resume Next
Set obj = CreateObject("MyObj.Test")

the script won't stop executing if the system can't create the object. However, use this statement with caution because it obscures the fact that an error has occurred. The system just executes the next instruction as if the previous instruction were successful. Countless times I discovered the culprit of a mysterious error to be a thoughtless On Error Resume Next statement.

A better approach is to use the On Error Resume Next statement with an If...Then...Else statement, as Listing 2 shows. With this approach, you still get a message stating that an error has occurred, but the script doesn't stop running.

If you use an On Error Resume Next statement inside a user-defined function, the system disables the statement as soon as the execution of the function terminates. If you want to disable error handling at a certain point in the script's main body, you can use the On Error Goto 0 statement. For example, if you run the code

On Error Resume Next
Set obj = CreateObject("MyObj.Test")
On Error Goto 0
Obj.Method

you won't get any error message for the failed object creation because the On Error Resume Next statement traps it. However, the On Error Goto 0 statement disables any valid error handler, and you get an error if obj isn't a valid object.

Err is worth mentioning, even though it's an object and not a statement. Because Err is a global object, you don't need to create an instance of (i.e., instantiate) it. As soon as the VBScript runtime traps an error, it automatically sets this object. You can interrogate Err to find out about the error. You use the code

On Error Resume Next
Set obj = CreateObject("MyObj.Test")
If Err.Number >0 Then MsgBox _ Err.Description

Err's Number property returns the number of the error, and its Description property returns the error description. Another property you can obtain is Source, which returns the name of the module in which the error originated. Although you don't need to instantiate Err, you do need to clear it when you've finished using it. You put the line

Err.Clear

immediately after the code you used to interrogate Err. You can also use the Raise method to find out information about errors, but I'll cover this method when I discuss user-defined functions in a future column.

If You Want to Learn More, Check These Out
I've provided an introductory look at the various conditional, loop, and error-handling statements. If you want to learn more about them, check out MSDN's various VBScript documents (http://msdn.microsoft.com/scripting/ default.htm?/scripting/ vbscript/techinfo/vbsdocs.htm). You can also check out the Windows Scripting Host (WSH) documents at http://msdn.microsoft.com/ scripting/default.htm?/scripting/ windowshost/docs/reference/default.htm.