About Me

Saturday 21 April 2012

VBScript While Loop

VBScript While Loop

A While Loop is a simple loop that keeps looping while something is true. Everytime it loops the block of code that is contained within the while loop is executed. The while loop is controlled by the same kind of conditional statement that you would see in an VBScript If Statement, so if you already know how an If Statement words, this lesson will be a breeze!

VBScript While Loop Example

In this lesson we will be creating a simple countdown that starts at 10 and ends with a BANG! First, we need to decide what our condition statement will be. Because we are counting down, it only seems logical that we would want our countdown variable to be greater than 0, otherwise we should be having a BANG!
The following code creates the while loop to create a simple VBScript countdown.

VBScript Code:

<script type="text/vbscript">
Dim counter
counter = 10
While counter > 0
    document.write(counter)
    document.write("<br />")
    counter = counter - 1
Wend
document.write("BANG!")
</script>

Display:

10
9
8
7
6
5
4
3
2
1
BANG!
The loop starts with the counter variable equal to 10 and subtracts one from counter each time through the loop. After 10 times(iterations) through the loop the conditional statement counter > 0 fails and the the while loop ends (Wend).

0 comments:

Post a Comment