www.pickatutorial.com Computer Tutorials
Top eBooks: C/C++ | C# | Android | Mathematics | Database | Cloud | Graphics | Networking | Oracle | Hardware | AI
Top Tutorials: C/C++ | C#.NET | PHP MySQL | Java | Java Script | jQuery | HTML | xHTML | HTML5 | VB Script| CSS
Lessons VBScript For and For Each Loop Bookmark and Share
Tutorial Home
Lesson 1
Lesson 2
Lesson 3
Lesson 4
Lesson 5
Lesson 6
Lesson 7
Lesson 8
Lesson 9
Lesson 10
Lesson 11
Lesson 12
Lesson 13
Lesson 14
In the previous lesson we learned to use the While loop. We learned that the While loop keeps repeating itself untill a given condition is true.

Another looping construct available in VBScript is the For Loop. Unlike the While loop, the For Loop does not take a condition, instead we provide a numeric variable to it and provide a minimum value to start the loop and a maximum value till we require the loop to keep iterating.

Here is an example:

<script type="text/vbscript">
For counter = 1 to 10
document.write("Loop Iteration No. " & counter & "<br>")
Next
</script>

Here is the output:

Loop Iteration No. 1
Loop Iteration No. 2
Loop Iteration No. 3
Loop Iteration No. 4
Loop Iteration No. 5
Loop Iteration No. 6
Loop Iteration No. 7
Loop Iteration No. 8
Loop Iteration No. 9
Loop Iteration No. 10

Here is how the above code works:
  • We start the loop by using the For keyword.
  • Next we provide a variable name followed by the equal (=) sign, the start value and the end value for the loop. In the above code we provide 1 as the start value for the loop and 10 as the end value for the loop, so that the loop executes 10 times.
  • Next we output some text and finally end our loop with the Next keyword.
  • Note that the variable name we provide is used, internally, by the VBScript interpreter to control the count of the loop.
  • After every iteration the loop control variable is increments by one, automatically.
For Each Loop
The VBScript For Each Loop allows us to iterate over an array. This is a quick and easy way of accessing all elements within an array without needing to know how many elements are in it.

Here is an example:

Dim fruits(3)
fruits(0) = "Orange"
fruits(1) = "Apple"
fruits(2) = "Mango"
For Each fruit In fruits
document.write(fruit)
document.write("<br />")
Next
</script>

Here is the output:

Orange
Apple
Mango

Here is how the above code works:
  • We define an array named fruits having 3 items and assign values to its every index.
  • We begin the loop with the keywords For Each followed by the name of a variable followed by the keyword In and the name of the array.
  • In the For Each loop body, on every iteration, we have a new item contained in the variable fruit, which we access and output to the browser window.
  • The keyword Next marks the end of the For Each loop block.

Next >>> Lesson No. 13: VBScript Functions




Home - Advertise - Contact - Disclaimer - About Us
© Since 2006 pickatutorial.com -- All Rights Reserved.