Looping Statements in VBScript

As you begin to create more complex scripts with VBScript you will develop the need to repeat sections of your code in order to repeat some actions. Looping statements provide a device for repeating code segments.

Contributed by
Rating: 5 stars5 stars5 stars5 stars5 stars / 5
December 11, 2007
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

VBScript provides several different looping statements that can be divided into two categories based on the way in which the loop is constructed: incremental loops and conditional loops.

Incremental loops are used to repeat code a definite number of times.  The number of iterations is determined at the time the loop is created.  This type of loop could be used to repeat a calculation a specific number of times or to move through each of the contents in an array since each of these would be repeated a definite number of times.

Conditional loops are used to repeat code based on the value of some conditional statement.  In other words, the code would be repeated for as long as a specified condition is true or false.  Looping will continue until that condition changes.  This allows you to repeat code an indefinite number of times.

Looping structures are not to be confused with methods such as subroutines or functions. These alternate methods of repeating code are designed to allow code to be reused without looping.  Viewing examples of both will make the separation between the two that much clearer.

More complex looping structures can be created by combining conditional loops and nesting multiple loops.  As you become more familiar with looping structures and more experienced in their implementation, you will begin to see how these complex loops can be beneficial.

Incremental Loops

VBScript uses the For…Next structure for creating incremental loops.  There are a few keyword variations that allow some flexibility in how the loop is executed.

For variable = intStart To intEnd [Step intIncrement]

      ' Code to be repeated

Next

A basic For…Next statement is used to repeat a section of code a definite number of times. The following code will count to 5 and print each number.

For x = 1 To 5

   WScript.Echo x

Next

The For statement requires that you supply a counter variable such as “x.” You must also supply its starting and ending value. The Next statement will increment the counter variable and repeat the enclosed code until it is no longer within the specified range, resulting in an output like the following:

1

2

3

4

5

The For statement also accepts the Step keyword which can be used to change the increment value. You may supply a negative number to cause the counter to decrement. The following example will list all even numbers from 10 to 0.

For x = 10 To 0 Step -2

   Wscript.Echo x

Next

Make sure that your starting value is less than your ending value when incrementing and greater than it when decrementing in order to prevent errors.  The second output looks like this:

10

8

6

4

2

0

Another variation of this loop is the For Each…Next loop.  This Each keyword will iterate through each element in a dictionary object, array, or collection.

arrWords = Array("one", "two", "three", "four", "five")

 

For Each strWord In arrWords

   WScript.Echo strWord

Next

In this example, I’ve created a simple string array. Using the For Each statement, I’ve iterated through each element without having to specify the number explicitly. The first variable in this statement must be a reference to the array element followed by the In keyword and a variable representing the array. The resulting output makes this very evident.

one

two

three

four

five

This same output can be generated using a simple For loop, however, the code is much more complex.

For i = 0 To UBound(arrWords)

   strWord = arrWords(i)

   Wscript.Echo strWord

Next

In this example, I’ve had to programmatically determine the number of elements in the array and then make a reference to each of them.  The For Each syntax is a much cleaner, quicker approach.

Conditional Loops

Conditional loops are constructed using the Do…Loop statements. VBScript provides the While and Until keywords to determine whether a loop should execute when a condition is true or false, respectively.

The conditional statement can be any statement or calculation that evaluates to either True or False. It can even be as simple as a Boolean value.

As you will see, the syntax of the Do…Loop statement is very flexible. I’ll demonstrate the most widely accepted versions first.

Do While | Until statement

      ' Code to be repeated

Loop

You must supply either the While or Until keyword followed by a conditional statement. Any conditional statement will work as long as it can be evaluated to either True or False. Comparisons and equality tests are the most common type of conditional statements found in Do loops.

x = 1

Do While x <> 5

   WScript.Echo x

   x = x + 1

Loop

The code above will continue outputting the value of x as long as it does not equal 5.  In other words it will execute “While x does not equal 5”.  This continues to execute as long as the condition is met providing the following output:

1

2

3

4

To see how the Until keyword processes false statements, we can modify the conditional statement above to its converse.

x = 1

Do Until x = 5

   WScript.Echo x

   x = x + 1

Loop

This loop will continue to execute “Until x equals 5.” A closer look shows that this loop will only continue to execute as long as the condition evaluates to false.

x = 1

Do Until x = 5

   WScript.Echo x

   x = x + 2

Loop

Take care when constructing your conditions.  Since x can never equal 5, the above code creates an endless or “infinite” loop because the condition can never be met.

The alternative Do…Loop syntax places the keyword and conditional statement in the closing statement instead.  While this is acceptable, it’s not widely used.

x = 1

Do

   WScript.Echo x

   x = x + 1

Loop Until x = 5

More On Loops

There is one final looping method that provides a conditional loop. The While…Wend provides a shorthand for the Do While…Loop syntax.  However, since it is less flexible its use has been depreciated.  Here’s an example of our first conditional loop:

x = 1

While x <> 5

   WScript.Echo x

   x = x + 1

Wend

A While…Wend loop will only continue to execute as long as its conditional statement evaluates to True.

From time to time you may wish to end the execution of a loop before it completes.  This can be done using the Exit statement.  Typically this will be used in conjunction with an IF statement to exit execution when an outside condition is met.

For x = 1 To 10

   WScript.Echo x

   If x = 5 Then

       Exit For

   End If

Next

 

arrWords = Array("one", "two", "three", "four", "five", _

   "six", "seven", "eight", "nine", "ten")

For Each strWord In arrWords

   WScript.Echo strWord

   If strWord = "five" Then

       Exit For

   End If

Next

 

x = 1

Do While x <> 10

   WScript.Echo x

   If x = 5 Then

       Exit Do

   End If

   x = x + 1

Loop

Each of the loops above has been modified so that it exits before execution completes. The output provided by these loops is the same as the previous examples even though the conditions have been changed to provide a much wider range of numbers.

1

2

3

4

5

one

two

three

four

five

1

2

3

4

5

Learning to use loops effectively can greatly increase the flexibility and power of your scripts.  Be sure to take the time to try nesting and combining your loops.  This can open up whole new avenues of scripting techniques for you to use.  Until next time, keep coding!

blog comments powered by Disqus
BRAINDUMP ARTICLES

- Microsoft Windows 8 Committed to Cloud Compu...
- Independent Developers Favor Windows Phone 7
- Dell Introduces VMware-based Cloud
- Microsoft and Skype Agree to Acquisition Deal
- Transfer Contacts in Microsoft Outlook
- Zune`s Next Steps
- Safari Books Online Review
- Does Microsoft Get Touch Screens Now?
- Microsoft`s Record Quarterly Earnings Not En...
- Basic Operations and Registers in Assembly
- Assembly Coding within Visual C/C++ IDE
- New Microsoft Office Coming with a Twist
- Microsoft`s FUSE Labs Unveils Spindex Social...
- HP Slate with Windows 7: Dead or Alive?
- Windows Phone 7 Mobile OS to Rival Android a...

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 10 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials