Previous Section Table of Contents Next Section

Loops

There will be times when you want VBScript to repeat the same task over and over. Perhaps you're having it evaluate a number of different files, or perhaps you simply want to make the computer beep a lot and annoy the person in the cube next to yours! Regardless of your motives, VBScript provides statements that make repetitive execution easy, and gives you full control over how many repetitions VBScript performs.

Do While…Loop and Do…Loop While

The Do While…Loop construct is used to execute a given section of code so long as a specified logical condition is true. Here's one way in which Do While…Loop can be used.


Dim iNumber

Do

 iNumber = InputBox("Please enter a number.")

Loop While Not IsNumeric(iNumber)

MsgBox "Thank you!"

This short script is an excellent example of collecting and validating user input. It starts by declaring a variable, iNumber. Next, VBScript enters the Do loop. Notice that there are no logical conditions specified with Do; it's on a line by itself, meaning VBScript will always execute the code within the loop.

Within the loop, VBScript uses an input box to collect user input, and assigns that input to the variable iNumber. The Loop statement contains the logic of the Do While…Loop construct: Not IsNumeric(iNumber). IsNumeric() is a function that evaluates a variable and returns True if the contents are numeric, and False otherwise. The Not Boolean operator tells VBScript to reverse the output of IsNumeric. So, if iNumber contains a number, the result of Not IsNumeric(iNumber) will be False, the opposite of what IsNumeric(iNumber) would return.

The Loop While statement tells VBScript to return to the Do statement whenever the logical expression is True. In this case, the logical expression will be True only if iNumber doesn't contain a numeric value. In other words, VBScript will continue asking for input repeatedly until that input is numeric.

When the input is finally numeric, VBScript stops executing the loop and responds with a message box reading, "Thank you!" and the script ends.

When you include a logical expression with Loop, VBScript always executes the code within the loop at least once. That's because VBScript executes code in the order in which it finds it, so it doesn't get to the Loop until it has already executed the code within the loop at least once. There may, however, be times when you don't want the script in the loop executed at all, unless a certain condition is true to begin with. For example, suppose you've written a script that opens a text file of unknown length. The file itself is represented by an object name oFile, and that object has an EndOfFile property that will be True when the end of the file is reached. You can use the Read method of the oFile object to read data from the file. In that case, you might use a section of script like this one to read through the entire file.


' assumes oFile is some kind of file object

' that is opened for reading

Dim sData

Do While Not oFile.EndOfFile

 sData = oFile.Read

 MsgBox sData

Loop

In this chunk of script, the logical condition is included with Do. Again, the Boolean Not operator is used to flip the output of the EndOfFile property. Therefore, the loop will continue to execute so long as EndOfFile is False.

NOTE

Another way to enter this logic would be Do While oFile.EndOfFile = False.


This loop does not necessarily execute at all. If oFile represents an empty file, EndOfFile will be True at the beginning of the loop. VBScript will evaluate this and skip the Do While…Loop construct completely, executing whatever code follows the Loop statement.

NOTE

You can include While and a logical expression with either Do or Loop, but not both.


Do Until…Loop and Do…Loop Until

The While statement in a Do…Loop construct tells VBScript to continue executing the loop so long as the specified condition is true. Until does exactly the opposite, executing the loop only until the specified condition becomes true. For example, you could rewrite the file reading sample as follows:


' assumes oFile is some kind of file object

' that is opened for reading

Dim sData

Do Until oFile.EndOfFile

 sData = oFile.Read

 MsgBox sData

Loop

In this case, the script will execute the same. VBScript simply performs the script until oFile.EndOfFile is True.

NOTE

The logical condition in this example could be written Do Until oFile.EndOfFile = True. However, you don't have to specify the = True part, because VBScript assumes it. If you don't specify some logical comparison using an equal sign, VBScript assumes that you meant to include = True.


Like While, Until can be included with either the Do or Loop statement. When you add it to the Loop, VBScript always executes the loop at least once, and then evaluates your Until expression to see if the loop should be executed again. When you include Until with Do, the loop only executes if the Until expression is False to begin with.

For…Next

Sometimes, you just need to execute a script a fixed number of times. For example, suppose you just want to make the computer beep eight times. Using a Do…Loop construct, you could write code like this.


Dim iCount

iCount = 1

Do Until iCount = 9

 Beep

 iCount = iCount + 1

Loop

This loop executes exactly eight times. However, it's quite a bit of code just to count from 1 to 8, and VBScript offers an easier way: For…Next. You can rewrite the preceding script as follows:


Dim iCount

For iCount = 1 To 8

 Beep

Next

When VBScript hits the For statement, it sets the specified variable (iCount) to the first specified value (1). Then, VBScript executes the loop's contents. When it reaches Next, VBScript increments the variable (iCount) by one and returns to the For statement for another go-round. When the value of iCount exceeds the specified range (greater than eight in this example), the loop stops executing and VBScript continues with whatever code follows Next.

Next increments the variable value by one by default, but you can control that. The following sample makes VBScript display the even numbers from 2 to 10.


Dim iCount

For iCount = 2 To 10 Step 2

 MsgBox iCount

Next

The Step statement tells VBScript to increment iCount by 2, rather than 1, each time it hits Next. You can specify a negative number to make Step go backward.


Dim iCount

For iCount = 10 to 1 Step -1

 MsgBox iCount

Next

MsgBox "Blast off!"

This sample will count down from 10 to 1 and then display "Blast off!"

For Each…Next

I've already introduced you to some objects that include collections, such as the FileSystemObject (which I'll discuss in full detail in Chapter 12). The tricky part about a collection of objects is that you may not know how many objects to expect in the collection. For Each…Next provides a useful way to work with each object in the collection, one at a time, without knowing exactly how many objects there are in the collection. Here's an example.


' Assume oRoot represents the root folder of C:\

' and has a Subfolders property that is a

' collection of folder objects that represent

' the subfolders of C:\

Dim oSubfolder

For Each oSubfolder In oRoot.Subfolders

 If oFolder.Name = "WINDOWS" Then

  MsgBox "Found the Windows folder!"

 End If

Next

VBScript goes through each object in the Subfolders collection, one at a time. For each object in the collection, VBScript assigns the object to the object reference variable oFolder and then executes the contents of the loop. WhenVBScript reaches Next, it sets oFolder to refer to the next object in the collection and executes the loop again. When VBScript finally reaches the end of the collection, it stops executing the loop and starts executing whatever code follows Next.

You'll see a lot more of For Each…Next in Chapter 12, which deals more fully with the FileSystemObject.

If you'd like a non-technical example, consider that Tree object I introduced in Chapter 5. Suppose the Tree object has a Leaves collection. Each object in the Leaves collection is a Leaf, and each Leaf object includes a Color property that retrieves that leaf's current color. You could use For Each…Next to count the number of yellow leaves.


Dim iYellowLeaves, oLeaf

' assumes oTree is a reference to the

' Tree object

For Each oLeaf in oTree.Leaves

 If oLeaf.Color = "Yellow" Then

  iYellowLeaves = iYellowLeaves + 1

 End If

Next



MsgBox "There are " & iYellowLeaves & _

 " yellow leaves on the tree."

Without knowing how many Leaf objects there are, For Each…Next efficiently steps through the collection one leaf at a time.

Exiting Loops

Suppose you don't always want a loop to finish executing. For example, take that file-reading script that I used in the Do While…Loop section earlier in this chapter. Suppose that what I really want to do is read through the file either until I reach the end of the file or until some calculation made on the file's contents is true. For example, suppose that the file contains a series of numbers, and I don't want to read any more data if the sum of those numbers exceeds 1000. Here's how I could do it.


' that is opened for reading

' assumes oFile is some kind of file object

Dim iData, iSum

Do Until oFile.EndOfFile

 iData = oFile.Read

 iSum = iSum + iData

 If iSum > 1000 Then

  Exit Loop

 End If

Loop

The key here is Exit Loop. If the value of iSum ever exceeds 1000, VBScript immediately exits the loop whether the Until condition was ever true. You can do the same thing in a For…Next loop.


Dim iCount, sInput

For iCount = 1 To 100

 sInput = "What's the password?"

 If sInput = "Sesame" Then

  Exit For

 End If

Next

In this example, VBScript will continue to ask "What's the password?" until you either type "Sesame" or until you've made 100 wrong guesses. The Exit For statement forces VBScript to exit the loop and begin executing whatever code it finds after the Next statement.

    Previous Section Table of Contents Next Section