Home > Articles > Home & Office Computing > Microsoft Windows Vista & Home Server

  • Print
  • + Share This
This chapter is from the book

Flow Control

It's all well and good that you can assign values to variables and perform calculations, but the real power of programming is in the ability to perform operations over and over, and to take different actions when conditions require. That's where flow control comes in. Instead of just executing each and every line of a program in order from top to bottom, conditional statements let you specify how the program is to respond to various situations it may encounter. With looping statements, you can execute certain statements repeatedly. Looping statements record not only how to handle a repetitive task but how to know when to start and stop the task.

The If...Then Statement

The If...Then statement examines what is called a condition, and if the condition is true, it executes one or more VBScript statements.

Consider this example:

         ' Example File script0201.vbs 
if Hour(Time()) < 12 then
    MsgBox "It's morning, rise and shine!"
end if

A condition is an expression that can be examined and found to be either true or false. In the preceding example, the condition is Hour(Time()) < 12. Now, in VBScript, Time() represents the current time of day, and Hour(Time()) represents the current hour of the day—a number from 0 to 23. From midnight until just before noon, this number is indeed less than 12, so the condition Hour(Time()) < 12 will be true, and the script will display the "It's morning" message. From noon on, the hour is 12 or greater, so the message will not be displayed. Figure 2.1 shows what I saw when I ran this script one morning.

Figure 2.1

Figure 2.1 The Good Morning message is displayed when the hour of the day is less than 12.

If...Then statements can control your script's behavior based on any kind of condition that can be written with a combination of VBScript variables, operators, and functions and that ends up as a Boolean (true/false) value.

The If...Then statement has several variations that help you manage more complex situations. First of all, when there is only one command you want to use if the condition is true, you can put the entire statement on one line:

if Hour(Time()) < 12 then MsgBox "It's morning, rise and shine!" 

If you need to use more than one statement when the expression is true, you must use the If...End If version; Then followed by a line break starts a block of commands, and End If marks the end of the statements that are executed when the condition is true. Here's an example:

if Hour(Time()) < 12 then 
    MsgBox "Good Morning!"
    runreport "Today's Activities"
    DeleteTemporaryFiles
end if

In this example, if the script is run before noon, the if statement runs the three statements between if and end if.

If you want to perform some commands if the condition is true, but other commands if the condition is false, you can use the If...Then...Else version of the command:

if condition then 
    vbscript commands to perform
    when condition is true
else
    vbscript commands to perform
    when condition is false
end if

Only one set of commands or the other will be performed when the script is run. Here's an example:

         ' example file script0202.vbs 
if Hour(Time()) < 12 then
    MsgBox "Good morning"
else
    MsgBox "Good day"
end if

If there is just one command in the Else section, you can put the command on the same line as else and omit the end if. Here are the four possible arrangements:

if condition then 
    statements
    . . .
else
    statements
    . . .
end if

if condition then
    statements
    . . .
else statement

if condition then statement else   ' note that else must go here
    statements
    . . .
end if

if condition then statement else statement

Finally, sometimes you'll find that one Else isn't enough. Another variation of the If command uses an ElseIf statement. With ElseIf, you test multiple conditions with one long statement:

if condition then 
    vbscript commands go here
elseif othercondition then
    other vbscript commands here
elseif yetanothercondition
    yet more commands
else
     last set of commands
end if

Again, only one of the sets of VBScript commands will be performed—the commands belonging to the first condition that is true. If none of the conditions turn out to be true, the optional Else statement will be used.

If you use ElseIf, you cannot use the all-in-one-line format.

Note that If statements can also be nested one inside the other for more complex situations, as shown here:

if filetype = ".EXE " then 
    if filename = "WINWORD" then
        MsgBox "The file is the WINWORD.EXE program"
    else
        MsgBox "The file is some other program"
    end if
else
    MsgBox "This is some other type of file"
end if

Here, the "inner" If statement is executed only if the variable filetype is set to ".EXE".

The Select Case Statement

Suppose I have different commands I want to run depending on the day of the week. You know from the preceding section that I could use a series of If and ElseIf statements to run one section of VBScript code depending on the day of the week. For example, I can assign to variable DayNumber a numeric value (using the constants vbMonday, vbTuesday, and so on) corresponding to the day of the week. Then, I can use a long If statement to handle each possibility:

DayNumber = Weekday(Date()) 
if DayNumber = vbMonday then
    MsgBox "It's Monday, Football Night on TV "
elseif DayNumber = vbTuesday then
    MsgBox "Tuesday, Music lessons"
elseif DayNumber = vbWednesday then
    MsgBox "Wednesday, Go see a movie"
elseif DayNumber = vbThursday then
    ... (and so on)
end if

However, there's an easier way. When you find that you need to perform a set of commands based on which one of several specific values a single variable can have, the Select Case statement is more appropriate. Here's an example:

         ' example file script0203.vbs 
DayNumber = Weekday(Date())
select case DayNumber
    case vbMonday:    MsgBox "It's Monday, Football Night on TV"
    case vbTuesday:   MsgBox "Tuesday, Music lessons"
    case vbWednesday: MsgBox "Wednesday, Go see a movie"
    case vbThursday:  MsgBox "Thursday, fishing!"
    case vbFriday:    MsgBox "Friday, Party Time!"
    case else:        MsgBox "Relax, it's the weekend!"
end select

When the Select Case statement is run, VBScript looks at the value of DayNumber and runs just those commands after the one matching Case entry. You can put more than one command line after Case entries if you want, and even complex statements including If...Then and other flow-of-control constructions. You can also specify a Case Else entry to serve as a catchall, which is used when the value of the Select Case expression doesn't match any of the listed values. In the example, Case Else takes care of Sunday and Saturday.

Although it's powerful and elegant, Select Case can't handle every multiple-choice situation. It's limited to problems where the decision that controls the choice depends on matching a specific value, such as Daynumber = vbWednesday or Username = "Administrator".

If your decision depends on a range of values, if you can't easily list all the values that have to be matched, or if more than one variable is involved in making the decision, you'll have to use the If...Then technique.

Here are some other points about the Select Case statement:

  • Statements can follow case value: on the same line or on a separate line. VBScript permits you to write

    case somevalue: statement 
    

    or

    case somevalue: 
       statement
    

    I usually use the all-on-one-line format when all or most of the cases are followed by just one statement, as in the days of the week example I gave earlier. When the statements after the cases are more complex, I start the statements on a new line and indent them past the word case.

  • If one set of statements can handle several values, you can specify these values after the word case. For example, you can type case 1, 2, 3: followed by VBScript statements.
  • If more than one case statement lists the same value, VBScript does not generate an error message. The statements after the first matching case are executed, and any other matches are ignored.
  • You can use a variable or expression as the case value. Here's an example:
    somevalue = 3 
    select case variable
        case somevalue:
            statements
        case 1, 2:
            statements
        case else
            statements
    end select
    

If the value of variable is 3, the first case statements will be executed. If the variable can take on values that are listed as other cases, remember that only the first match will be used.

The Do While Loop

Many times you'll want to write a script where you don't know in advance how many items you'll have to process or how many times some action will need to be repeated. Looping statements let you handle these sorts of tasks. As a trivial example, the task of folding socks might be described in English this way:

as long as there are still socks in the laundry basket, 
   remove a pair of socks from the basket
   fold them up
   place them in the sock drawer
repeat the steps

In VBScript, we have the Do While statement to repeat a block of code over and over. In VBScript, the laundry-folding task might look like this:

do while NumberOfSocksLeft >= 2 
   MatchUpSocks
   FoldSocks
   PutSocksAway
   NumberOfSocksLeft = NumberOfSocksLeft - 2
loop

Here, the Do While part tells VBScript whether it's appropriate to run the statements following it, and Loop sends VBScript back to test the condition and try again. Do While statements can be nested inside each other, if necessary. Each Loop applies to the nearest Do While before it:

do while somecondition 
    ... statements
    do while SomeOtherCondition
       ... more statements
    loop
    ... still more stuff perhaps
loop

As you can see, indenting the program statements inside each Do While statement helps make this easy to read and follow.

There are actually five versions of the Do While loop, each subtly different:

do while condition 
    statements
loop

do until condition
    statements
loop

do
    statements
loop while condition

do
    statements
loop until condition

do
   statements
   if condition then exit do
   statements
loop

With the first version, VBScript evaluates the Boolean condition. If its value is True, VBScript executes the statement or statements inside the loop and goes back to repeat the test. It executes the set of statements repeatedly, every time it finds that condition is still True.

The second version loops again each time it finds that condition is False—that is, until condition becomes True. You could also write

do while not (condition) 
    statements
loop

and get the exact same result. Why have both versions? Sometimes you'll want to write "while there are more socks in the laundry basket" and sometimes you'll want to write "until the laundry basket is empty." The While and Until versions are provided so that you can use whichever one makes more intuitive sense to you.

Notice, though, that in these first two versions, if the While or Until condition fails before the first go-round, the statements inside will never be executed at all. In the second two versions, notice that the test is at the end of the loop, so the statements inside are always executed at least once.

The last version shows how you can end the loop from the inside. The exit do statement tells VBScript to stop running through the loop immediately; the script picks up with the next statement after the end of the loop. In this fifth version, the loop always executes at least once, and the only test for when to stop is somewhere in the middle. You can actually use exit do in any of the five variations of Do While. I'll discuss exit do more in the next section.

Every time you write a script using a Do While, you should stop for a moment and think which is the most appropriate version. How do you know which to use? You'll have to think it through for each particular script you write, but in general, here's the pattern to use:

Terminating a Loop with Exit Do

Sometimes it's desirable to get out of a Do While or other such loop based on results found in the middle of the statements inside, rather than at the beginning or end. In this case, the Exit Do statement can be used to immediately jump out of a loop, to the next command after the loop line.

For example, suppose you expect to be able to process five files, named FILE1.DAT, FILE2.DAT, and so on. However, if you find that a given file doesn't exist, you might want to stop processing altogether and not continue looking for higher numbered files. The following shows how you might write this up in a script:

set fso = CreateObject("Scripting.FileSystemObject") 
num = 1
do while num <= 5                              ' process files 1 to 5:
    filename = "C:\TEMP\FILE" & num & ".DAT"   ' construct filename
    if not fso.FileExists(filename) then       ' see file exists
        exit do                                ' it doesn't, so terminate early
    end if
    Process filename                           ' call subroutine "process"
    num = num + 1                              ' go on to next file
loop

In this example, the first time through the loop, we set variable filename to FILE1.DAT. Each turn through increments variable num by one. We test to be sure the file whose name is stored in variable filename really exists. If the file does not exist, Exit Do takes the program out of the loop before it attempts to process a missing file.

There's no reason we have to limit the Do While loop to a fixed number of turns. If we omit the "do" test entirely, it will run forever. The constant True is just what it sounds like, so we could rewrite the previous script to process as many files as can be found, from 1 to whatever:

         ' example file script0204.vbs 
set fso = CreateObject("Scripting.FileSystemObject")
num = 1
do                                  ' process as many files as found
   filename = "C:\TEMP\FILE" & num & ".DAT"    ' construct filename
   if not fso.FileExists(filename) then        ' see file exists
      exit do                                  ' no, terminate early
   end if
   Process filename                            ' call subroutine "process"
   num = num + 1                               ' go on to next file
loop

Here, without a While or Until clause, the loop runs indefinitely (it's what programmers call an infinite loop), until Exit Do ends it. This means that you have to be careful that Exit Do eventually does get executed; otherwise, your script will churn through the loop forever (or until your patience runs out and you cancel it by typing Ctrl+C).

The Exit Do statement works in any of the four variations of Do While and Do Until statements.

Counting with the For...Next Statement

When a loop needs to run through a set number of iterations, the For...Next statement is usually a better choice than the Do While statement. The first example I used for Exit Do can be rewritten as a For loop like this:

         ' example file script0205.vbs 
set fso = CreateObject("Scripting.FileSystemObject")
for num = 1 to 5                                  ' process files 1 to 5:
     filename = "C:\TEMP\FILE" & num & ".DAT"     ' construct filename
     if not fso.FileExists(filename) then         ' see file exists
         exit for                                 ' no, terminate early
     end if
     Process filename                             ' call subroutine "process"
next

The For loop sets a variable (num, in this example) to the first value (here, 1) and processes the statements inside. It then increments the variable and repeats the statements until the variable is larger than the number after To (here, 5). This loop thus processes the statements with num = 1, 2, 3, 4 and 5.

In the example, I also used the Exit For statement, which works exactly like Exit Do, except that it breaks out of a For loop rather than a Do loop. (Makes sense, doesn't it?!) The Exit For statement makes VBScript continue processing the script with the line after Next.

The For statement can be written in either of two ways:

for counter = startvalue to endvalue 

or

for counter = startvalue to endvalue step stepvalue 

Here, counter is the variable to be used; startvalue is the value that the variable is to take the first time through the loop; endvalue is the largest value the variable is to take; and stepvalue, if specified, is the value by which to increment counter each time through. The stepvalue can be negative if you want your loop to count backward, as in this rendition of a well-known, irritating song:

         ' example file script0206.vbs 
for number_of_bottles = 100 to 0 step -1
     wscript.echo number_of_bottles & " bottles of beer on the wall!"
next

If the Step clause is left out, the counter variable is incremented by one each time.

Processing Collections and Arrays with For...Each

Some special-purpose VBScript functions can return a variable type called a collection. A collection is a list of filenames, usernames, or other data contained in a single variable. For example, a directory-searching function might return a collection of filenames when you ask for all files named *.DOC. Because you'll probably want to print, view, or manipulate these files, you need a way of accessing the individual items in the collection.

The For...Each loop runs through the loop once for each item in a collection. Here's an example:

         ' example file script0207.vbs 
set fso = CreateObject("Scripting.FileSystemObject")
set tempfiles = fso.GetFolder("C:\TEMP").Files

filelist = ""
for each file in tempfiles
    filelist = filelist & ", " & file.name
next

MsgBox "The temp files are:" & filelist

In this example, the variable tempfiles is set to a collection of all the files found in folder C:\TEMP. The For...Each loop creates a variable named file, and each time through the loop it makes variable file refer the next object in the collection. The loop runs once for each file. If the collection is empty—that is, if no files are included in folder C:\TEMP—then the loop doesn't run at all. You also can use the For...Each statement with array variables, executing the contents of the loop once for each element of an array, as shown in this example:

dim names[10] 
...
for each nm in names
    ...
next

The VBScript statements inside this loop will be executed 10 times, with variable nm taking one each of the 10 values stored in names in turn.

To learn more about arrays, see "Arrays," p. 79.

You can use any variable name you want after for each; I chose names file and nm in the examples because they seemed appropriate. You can use any valid variable name you wish.

  • + Share This
  • 🔖 Save To Your Account