Quackit Logo

Got a MySpace Page?

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

VBScript For Loop

Print Version

The VBScript For Loop allows you to execute code for a given number of iterations. Using a For loop, you provide a given expression, and the loop will iterate for as long as that expression results to true.

Example For Loop

Using the same scenario as the previous lesson, the loop will iterate from 0 to 8. It will then continue processing the rest of the page.

<script type="text/vbscript">
  For hoursWorked = 0 to 8
    document.write("Hours worked: " & hoursWorked)
    document.write("<br />")
  Next
    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!

For Each Loop

The VBScript For Each Loop allows you to iterate over an array. This can be a quick and easy way of accessing all elements within an array without you needing to know how many elements are in it.

<script type="text/vbscript">
  Dim shoppingList(3)
  shoppingList(0) = "Bananas"
  shoppingList(1) = "Bread"
  shoppingList(2) = "Pasta"
  For Each listItem In shoppingList
  document.write(listItem)
  document.write("<br />")
Next
</script>

This results in:

Bananas
Bread
Pasta

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!