About Me

Saturday 21 April 2012

VBScript For Loop

VBScript For Loop

A For Loop is used for special situations when you need to do something over and over again until some condition statement fails. In a previous lesson, VBScript Arrays we used a For Each loop to print out every item in our VBScript array.

The For Loop and the For Each Loop are very useful if you know how to use them. This lesson will teach you the basics of each type of for loop.

VBScript For Loop

VBScript For Loops are a little different compared to conventional for loops you see in programming languages like C++ and Java, so pay extra close attention! The For Loop has a counter variable that is created specifically to keep track of how many times the loop's code has been executed. After each successful execution of the loop VBScript automatically adds 1 to this counter variable and keeps doing this until the MAX is reached.
Here is the pseudo code for a VBScript For Loop:
  • For counterVariable = 0 to MAX
You would replace counterVariable with the name of your counter (most often counter variable used is i). MAX would also be replaced with an integer to specify how many times you would want the For Loop's code executed.

VBScript For Loop Example

To clearly illustrate how a For Loop works in the real world, the following example will print out the counter variable to the browser after each successful loop.

VBScript Code:

<script type="text/vbscript">
For count = 0 to 3
    document.write("<br />Loop #" & count)
Next

</script>

Display:

Loop #0
Loop #1
Loop #2
Loop #3
You can see here that the loop executes 4 times, once for 0, 1, 2 and 3.

VBScript For Each Loop

VBScript For Each Loop is useful when you want to go through every element in an array, but you do not know how many elements there are inside the array.
The following example creates an array and then prints out every element.

VBScript Code:

<script type="text/vbscript">
Dim myCloset(2)
myCloset(0) = "Coat"
myCloset(1) = "Suit"
myCloset(2) = "Boxes"

document.write("In my closet is:")
For Each item In myCloset
    document.write(item & "<br />")
Next
</script>

Display:

In my closet is:Coat
Suit
Boxes

0 comments:

Post a Comment