Quackit Logo

Got a MySpace Page?

Get "www.yourname.com" for your MySpace page. Learn how >>.

VBScript While Loop

Print Version

In VBScript (and virtually all other languages), "loops" enable your program to continuously execute a block of code for a given number of times, or while a given condition is true.

The VBScript While Loop executes code while a condition is true.

Example While Loop

This example displays a the value of a counter while the count is less than or equal to 8.

<script type="text/vbscript">
  Dim hoursWorked
  hoursWorked = 0
  While hoursWorked <= 8
    document.write("Hours worked: " & hoursWorked)
    document.write("
") hoursWorked = hoursWorked + 1 Wend
document.write("Home time!") </script>

This results in:

Hours worked: 0
Hours worked: 1
Hours worked: 2
Hours worked: 3
Hours worked: 4
Hours worked: 5
Hours worked: 6
Hours worked: 7
Hours worked: 8
Home time!

Exlanation of code

  1. We started by declaring a variable called "hoursWorked" and setting it to 0
  2. We then opened a while loop and inserted our condition. Our condition checks if the current value of the hoursWorked variable is less than or equal to 8.
  3. This is followed by code to execute while the condition is true. In this case, we are simply, outputting the current value of hoursWorked, preceded by some text.
  4. We then increment the value by 1.
  5. When the browser reaches the closing curly brace, if the condition is still true, it goes back to the first curly brace and executes the code again. By now, the hoursWorked variable has been incremented by 1. If the condition is not true (i.e. the variable is greater than 10), it exits from the loop, and continues on with the rest of the code.

Enjoy this website?

  1. Link to this page (copy/paste into your own website or blog):
  2. Add this page to your favorite social bookmarks sites:
                     
  3. Add this page to your Favorites

Oh, and thank you for supporting Quackit!