Conditional Logic and Iterative Structures

In this chapter, you will learn how to set up conditional tests within VBScripts using VBScript's If and Select Case statements. Using these statements, you will be able to perform tests that compare two different values or expressions and alter the logical flow of scripts based on the results of those tests.

In addition, this chapter covers iterative structures. VBScript's iterative statements include the Do…While, Do…Until, For…Next, While…Wend, and For Each…Next statements. These programming constructs provide you with the ability to iterate (or loop) through a series of object properties or to iterate a specified number of times in order to develop processes capable of manipulating large amounts of data.

Comparison Statements

VBScript provides two different statements that allow you to perform conditional logic tests between two expressions or values. These statements are outlined below.

  • If. A statement that compares two expressions and performs or skips the execution of a portion of the script based on the results of the comparison
  • Select Case. A formal programming construct that allows a programmer to visually organize program execution based on the outcome of a comparison between an expression and a list of possible matching expressions

The If and Select Case statements provide VBScript with the intelligence required to test data and modify the execution of the logical flow of the scripts in order to accommodate different situations.

The If Statement

The If statement performs a comparison between two expressions and then directs the logical execution of the scripts based on the results of that comparison. The syntax of the If statement is outlined below.

If condition Then
 statements
ElseIf condition-n Then
 elseifstatements
.
.
.
Else
 elsestatements
End If

condition is the expression to be tested. statements represents one or more statements that are to be executed if the result of the tested condition proves true. condition-n is an optional alternative condition to test, and elseifstatements are one or more statements that are to be executed if the results of ElseIf test prove to be true. elsestatements are one or more optional statements to be executed in the event that none of the previous tests prove true.

If Statement Usage

The If statement can be used in several forms. To perform a simple comparative test, all that is required is the If keyword, the expression to test, and the Then keyword followed by a statement to execute if the tested condition proves true. For example, the following statement performs a conditional test to determine whether the value of intUnitCount is equal to 100:

If intUnitCount = 100 Then MsgBox "Time to place a new inventory order"

You can set up an If statement to execute more than one statement when the tested condition proves true by adding the End If keyword as demonstrated below.

If intUnitCount = 100 Then
 MsgBox "Time to place a new inventory order"
 strOrderStatus = "In Progress"
End If

Advanced Comparison Operations

In each of the previous If statement examples, the equal operator was used to determine whether the value of the two expressions was equal. While this is certainly a useful operation, in many cases you will need to perform conditional tests based on other criteria, such as a not equal to condition or a range of possible conditions. VBScript provides you with a number of different comparison operators, outlined in Table 3.1, that allow you to perform any number of complex conditional tests.

Table 3.1: VBScript Comparison Operators

Operator

Description

=

Equal

<>

Not equal

>

Greater than

<

Less than

>=

Greater than or equal to

<=

Less than or equal to

For example, using the previous example of code, you can modify the If statement to determine whether the value of intUnitCount is less than or equal to 100, as shown below.

If intUnitCount <= 100 Then
 MsgBox "Time to place a new inventory order"
 strOrderStatus = "In Progress"
End If

Alternative Forms of the If Statement

In the previous example, the If statement defines which course of action to take if the tested condition proves to be true. To provide an alternative execution path (for example, when the tested condition proves to be false), you need to add the Else keyword, as demonstrated below.

If intUnitCount < 100 Then
 MsgBox "Time to place a new inventory order"
 strOrderStatus = "In Progress"
Else
 MsgBox "Current inventory levels are within specified limits"
End If

You can modify the example above to accommodate alternative tests in the event that the previous comparison proves to be false. This is achieved by adding the ElseIf keywords, as follows.

If intUnitCount < 100 Then
 MsgBox "Time to place a new inventory order"
 strOrderStatus = "In Progress"
ElseIf intUnitCount < 150 Then
 MsgBox "Inventory levels are within acceptable limits"
 strOrderStatus = "Not in Process"
ElseIf intUnitCount > 200 Then
 MsgBox "Current inventory levels are at maximum"
 strOrderStatus = "Not in process"
End If

Nesting Multiple If Statements

VBScripts allow you to embed (or nest) one If statement within another in order to perform more complicated logic and to further refine the analysis of tested conditions, as demonstrated below.

If intUnitCount < 100 Then
 If Weekday(date()) = 1 Then 'If it is Sunday
 MsgBox "Wait until Monday to place a new inventory order"
 Else
 MsgBox "Time to place a new inventory order"
 End If
Else
 MsgBox "Current inventory levels are within specified limits"
End If

These is no limit to the number of layers of embedded If statements you can use. However, from a practical standpoint, going more than a few layers deep becomes confusing for most people.

The Select Case Statement

The If statements provide an effective mechanism for testing the value of two expressions. However, in situations where you need to compare a single expression against a number of possible matching expressions, VBScript provides the option of using the Select Case statement.

The syntax of the Select Case statement is shown below.

Select Case testexpression
 Case expressionlist-n
 liststatements
 .
 .
 .
 Case Else
 elsestatements
 End Select

testexpression is the expression that will be compared to other expressions specified by one or more Case statements. liststatements represents one or more VBScript statements that will be executed in the event that one of the expressions specified by one of the Case statements equals the value of testexpression. elsestatements are VBScript statements that will be executed in the event that none of the expressions specified by the Case statements prove equal to testexpression.

The following example demonstrates how to use the Select Case statement.

Select Case Weekday(date())
 Case vbSunday
 MsgBox "Today is Sunday"
 Case vbMonday
 MsgBox "Today is Monday"
 Case vbTuesday
 MsgBox "Today is Tuesday"
 Case vbWednesday
 MsgBox "Today is Wednesday"
 Case vbThursday
 MsgBox "Today is Thursday"
 Case vbFriday
 MsgBox "Today is Friday"
 Case vbSaturday
 MsgBox "Today is Saturday"
End Select

In this example, the VBScript Date() function is used to retrieve the current system date. The result is then fed to the VBScript Weekday() function, which returns a value representing the day of the week. The resulting value is then compared to the seven VBScript date constants specified by Case statements, each of which represents a different day of the week, to determine which MsgBox() statement to execute.


Working with Loops

VBScript provides a number of statements that allow you to establish loops within your scripts. Loops provide the ability to efficiently process large amounts of data using a minimal number of programming statements. These statements are outlined below.

  • Do…While. Sets up a loop that iterates as long as a specified condition remains true
  • Do…Until. Sets up a loop that iterates until a specified condition becomes true
  • For…Next. Sets up a loop that iterates for a specified number of times
  • While…Wend. Sets up a loop that iterates as long as a specified condition remains true
  • For Each…Next. Sets up a loop that iterates through a list of properties belonging to a specified object

Do While

The Do…While statement repeatedly executes a collection of statements as long as a specified condition remains true. VBScript provides two different forms of the Do…While statement. In the first version, the Do…While loop only begins processing if the tested condition is initially true. Its syntax is shown below.

Do While condition
 statements
Loop

condition is the expression that is to be tested, and statements represents one or more VBScript statements to be executed upon each iteration of the loop. For example, the following statements create a loop that will execute until the value of intCounter equals 5.

strMessageString = "Watch me count!" & vbCrLf & vbCrLf
intCounter = 0
Do While intCounter < 10
 intCounter = intCounter + 1
 strMessageString = strMessageString & intCounter & " "
Loop
MsgBox strMessageString

In this example, a loop is set up to execute while the value of intCounter, which is initialized with a value of zero, is less than 10. Each time the loop iterates, it increases the value of intCounter by 1 and appends the value of intCounter to the end of a string. When the loop finally terminates, the script displays the message string shown in Figure 3.1.

click to expand
Figure 3.1: Using a Do…While loop to demonstrate how to count to 10

Because the While keyword was placed at the beginning of the loop, the loop executes only if the tested condition is initially true. The second form of the Do…While statement moves the While keyword to the end of the loop, forcing the loop to process once, regardless of whether the condition that it is testing is initially true. The syntax for this form of the Do…While statement is outlined below.

Do
 statements
Loop While condition

The following example shows a small VBScript that uses the second form of the Do…While loop to collect data from the user. In the case of this example, the script prompts the user to type a name, a part number, and a quantity of a product to be included on a reorder report. Data collection is achieved using the VBScript InputBox() function.

  Note

The InputBox() function displays a message in a pop-up dialog box and collects user input, which can then be validated and processed by your scripts. More information on the InputBox(), including its syntax and usage, is provided in Chapter 6, "Data Collection, Notification, and Error Reporting."

'*************************************************************************
'Script Name: Script 3.1.vbs
'Author: Jerry Ford
'Created: 01/04/2003
'Description: This script demonstrates how to collect user input using a
'Do...While loop
'*************************************************************************

'Initialization Section

Const cTITLEBARMSG = "Inventory Order Report"

Dim intCounter, strInventoryOrder, intPartNumber, intQuantity, strInvReport

intCounter = 0


'Main Processing Section

Do

 intCounter = intCounter + 1

 strInventoryOrder = InputBox("Please type the name of the product to be " & _
 "ordered or type {Quit} when done.", cTITLEBARMSG)

 If Len(strInventoryOrder) = 0 Then

 MsgBox "Either type a product to be ordered or type Quit", ,cTITLEBARMSG
 Else

 If UCase(strInventoryOrder) <> "QUIT" Then
 intPartNumber = InputBox("Please type the part number for " & _
 strInventoryOrder, cTITLEBARMSG)
 intQuantity = InputBox("How many units should of " & strInventoryOrder & _
 " should be ordered?", cTITLEBARMSG)
 strInvReport= strInvReport & intCounter & ". " & "Item: " & _
 strInventoryOrder & _
 " Part No: " & intPartNumber & " Quantity: " & intQuantity & vbCrLf
 End If

 End If
Loop While UCase(strInventoryOrder) <> "QUIT"

If Len(strInvReport) > 0 Then
 MsgBox strInvReport, ,cTITLEBARMSG
End If

Each time through the loop, a variable called intCounter is incremented. This variable is used to track the number of times that the loop has iterated. It is also used later in the script to help organize the reorder list by assigning a number to each item in the list.

The first thing that this script does is to ask the user to either enter a product name or type Quit to exit the script. It stores the user's response in a variable called strInventoryOrder. Next, the script checks to see if the length of strInventoryOrder is equal to zero. If it is, then the user clicked either on the Cancel button or on the OK button without entering a product name. In this case, the script displays instructions in a pop-up dialog box informing the user how to properly use the script.

If the length of strInventoryOrder is not equal to zero, then the script checks to see if the user typed the word Quit. The script uses the VBScript Ucase() function to convert the user's input to all uppercase to eliminate any confusion over case and then uses a If statement to see if the user typed Quit. If the user typed Quit, then the Do…While loop terminates. Another If statement follows, which checks the length of the display string used to contain the reorder report. If the length of this string is equal to zero, then the user typed Quit without ever entering any data, so there is nothing to display. Otherwise the data entered by the user is displayed in a pop-up dialog box.

If the user did not type Quit, then the user is prompted, via two more Input-Box() statements, as demonstrated in Figure 3.2, to supply a part number and a quantity for each unit to be ordered. The information collected from the user is then concatenated together into a string that will later be used to display the data in report form. The VBScript vbCrLf constant is used to format the string by executing a form feed and carriage return at the end of each set of data that is collected as shown in Figure 3.3. This script is relatively simple and performs only a limited amount of validation. However, it serves to demonstrate the power provided by the Do…While loop as well as VBScript's ability to collect and process user input.

click to expand
Figure 3.2: Using a Do…While loop to collect and process user input

click to expand
Figure 3.3: An example of the output produced by the script

Do Until

Unlike the Do…While statement, which executes as long as a condition remains true, the Do…Until statement executes until a condition becomes true. Like the Do…While statement, the Do…Until statement is supported in two forms. In its first form, the Until keyword is placed at the beginning of the loop. The syntax for this version of the Do…Until loop is shown below.

Do Until condition
 statements
Loop

condition represents the expression to be tested; statements represents VBScript statements that will be executed during each iteration of the loop. The following example shows this version of the Do…Until loop in action.

Dim intCounter, strContactName, strContactList

MsgBox "This script collects the name of up to 5 personal contacts."

intCounter = 0

Do Until intCounter = 5

 strContactName = InputBox("Please enter the name of a personal contact.")

 If Len(strContactName) = 0 Then
 Exit Do
 End If

 intCounter = intCounter + 1

 strContactList = strContactList & intCounter & ". " & strContactName & vbCrLf

Loop

If Len(strContactList) <> 0 Then
 MsgBox strContactList
End If

In this example, a loop is set up that uses the VBScript InputBox() to collect the name of up to five personal contacts. The loop runs until the user either types the names of five contacts or terminates loop execution by clicking on Cancel (or by clicking on OK without entering anything).

The second form of the Do…Until statement moves the Until keyword to the end of the loop. The syntax for this form of the loop is shown below.

Do
 statements
Loop Until condition

condition represents the expression to be tested, and statements represents VBScript statements that will be executed during each iteration of the loop. Because the Until keyword is now at the end of the loop, the programmer can be assured that the loop will go through at least one iteration.

For Next

The For…Next loop is used to set up a loop that executes for a specific number of iterations. The syntax for the For…Next statement is shown below.

For counter = begin To end [Step StepValue]
 statements
Next [counter]

counter is a variable that the loop uses to track the number of times that it has iterated and statements represents VBScript statements that will be executed during each iteration of the loop. begin specifies the starting value of counter. end specifies its ending value. StepValue specifies the value that counter will be incremented by upon each iteration of the loop.

The For…Next loop can easily be used to rewrite the previous example, as shown below.

Dim intCounter, strContactName, strContactList

MsgBox "This script collects the name of up to 5 personal contacts."

For intCounter = 1 To 5

 strContactName = InputBox("Please enter the name of a personal contact.")

 If Len(strContactName) = 0 Then
 Exit For
 End If

 strContactList = strContactList & intCounter & ". " & strContactName & vbCrLf
Next

If Len(strContactList) <> 0 Then
 MsgBox strContactList
End If

The nice thing about working with the For…Next loop is that it is easy to adjust the loop to change the number of iterations. For example, to enable the previous example to collect 20 personal contacts instead of 5, only one following statement needs to be changed, as shown below.

For intCounter = 1 To 20

Using the optional Step keyword, you can change the value that the For…Next loop uses to increment upon each iteration of the loop. For example, the following statements create a For…Next loop with a beginning value of 1 and an ending value of 9.

Dim intCounter
For intCounter = 1 To 20 Step 3
 WScript.Echo intCounter
Next

When saved as a script file with a .VBS file extension and run using the Script.exe execution host, this script displays the following output.

C:>cscript "Script 3.2.vbs"
Microsoft (R) Windows Script Host Version 5.6
Copyright (C) Microsoft Corporation 1996-2001. All rights reserved.

1
4
7
10
13
16
19

C:>

While Wend

The While…Wend statement can be used to create a loop that executes as long as a condition remains true. The syntax for this statement is outlined below.

While condition
 statements
Wend

condition is an expression that is being tested, and statements represents VBScript statements that will be executed during each iteration of the loop. The While…Wend statement is provided for backward compatibility purposes. Its continued use is discouraged. Its functionality is duplicated by the Do…While and Do…Until statements, which are more flexible in their application.

For example, the following HTML page includes a VBScript that uses a While…Wend loop to build a string that counts from 1 to 10, as demonstrated in Figure 3.4.

click to expand
Figure 3.4: Using the While…Wend loop in a VBScript embedded inside a HTML page


 

Script 3.3 - A While...Wend example

For Each Next

The For Each…Next loop provides the ability to programmatically iterate through all of the properties belonging to an object or all the elements stored in an array. The syntax for the For Each…Next loop is outlined below.

For Each element In collection
 statements
Next [element]

element is a variable that represents an object's property or an element stored in an array. collection is the name of the object or array. statements represents the VBScript statements that are executed during each iteration of the loop.

For example, using the For Each…Next loop, you can write a WSH VBScript that can process the file contents of any Windows folder, as demonstrated below.

'*************************************************************************
'Script Name: Script 3.4.vbs
'Author: Jerry Ford
'Created: 01/04/2003
'Description: This script demonstrates how to use the For Each...Next
'loop to process all the files stored in a folder
'*************************************************************************

'Initialization Section

Option Explicit

Dim FsoObject, FolderName, Member
Dim strFileList, intCounter

Set FsoObject = CreateObject("Scripting.FileSystemObject")
Set FolderName = FsoObject.GetFolder("C:Temp")

intCounter = 0


'Main Processing Section

For Each Member in FolderName.Files
 intCounter = intCounter + 1
 strFileList = strFileList & intCounter & ". " & Member.name & vbCrLf
Next

MsgBox strFileList, ,"List of files in " & FolderName

In order to complete this script, the VBScript FileSystemObject had to be used. This object is a VBScript run-time object that will not be formally introduced in this book until Chapter 17, "Using Configuration Files to Control Script Execution." Therefore, only a minimal explanation will be provided here.

This script begins by defining the variables that it will use. It then instantiates an instance of the FileSystemObject and sets up a reference to the location of the target folders using its GetFolder() method. Next, a For Each…Next loop executes, processing all the files found in the target folder by adding them to a numbered list stored as a string. Finally, the last statement in the script displays the string built by the For Each…Next loop, producing the output shown in Figure 3.5.

click to expand
Figure 3.5: Using a For Each…Next loop to iterate through the contents of a folder

For Each…Next loops can also be used to process the contents of VBScript arrays. In this situation, you simply specify a variable representing each element in the array and the name of the array, as demonstrated below.

For Each Member In TestArray
 statements
Next

In this example, the name of the array is TestArray and statements is used to represent any number of VBScript statements required to process each element stored in the array.

  Note

To learn more about arrays and how to process them, refer to Chapter 5, "Arrays."


Guarding against Endless Loops

Whenever programmers work with loops, they run the risk of accidentally creating an endless loop. For example, the following Do…While loop does exactly this.

intCounter = 0
Do While intCounter < 10
 intCounter = intCounter - 1
Loop

Instead of incrementing the value of intCounter each time through the loop, the script is set to decrement its value by 1. Since the value of intCounter will never be greater than 10, a endless loop has been accidentally created. To guard against this predicament, some programmers add an additional counter to their loops as a sort of "safety net," as demonstrated below.

intCounter = 0
intNoExecutions = 0
Do While intCounter < 10
 intCounter = intCounter - 1
 intNoExecutions = intNoExecutions + 1
 If intNoExecutions > 50 Then
 MsgBox "Script execution terminating: Possible Endless Loop!"
 Exit Do
 End If
Loop

As you can see, a second variable has been added that tracks the number of iterations that the loop performs and is used to terminate the loop's (not the script's) execution if more than 50 iterations occur. By cutting and pasting a tried and true loop safety net into your scripts during testing and development, you can save time by preventing endless loops that would otherwise crash your computer or force you to take steps to manually terminate runaway scripts. Once your scripts are tested and ready for production, you can always remove the extra code.

  Note

The previous example introduced the use of the Exit Do statement. This statement is used to terminate the execution of a Do…While or Do…Until loop. It can only be used inside one of these two types of loops. When executed, the Exit Do statement switches processing control to the statement immediately following the loop.

The Exit Do statement is one of five variations of Exit statements. These other statements include:

  • Exit For
  • Exit Function
  • Exit Property
  • Exit Sub


Summary

In this chapter, you learned about VBScript's decision-making capabilities, which are provided in the form of the If and Select Case statements. You also examined VBScript's support for iterative processing, including a review of the Do…While, Do…Until, For…Next, While…Wend, and For Each…Next statements. By combining the capabilities of these two groups of programming statements, you will be able to create VBScripts that can process large amounts of information and alter their own logical execution based on the data that they are presented with.






Microsoft VBScript Professional Projects
Microsoft VBScript Professional Projects
ISBN: 1592000568
EAN: 2147483647
Year: 2005
Pages: 366
Simiral book on Amazon

Flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net