For...Next Loop

Now we'll take a quick look at another kind of loop: the For...Next loop. In this kind of loop, we don't need to worry about infinite loops. This is because the loop is predefined to only execute a certain number of times. Here's a simple example:

Dim Index
MsgBox "Let's count to five. Ready?"
For Index = 1 to 5
MsgBox Index
Next
MsgBox "Wasn't that fun?"

The beginning loop block is defined by the For statement, and the end is defined by the Next statement. This loop will go around exactly five times. The line For Index = 1 to 5 essentially tells the script engine, "Execute this block of code as many times as it takes to count from 1 to 5, and use the Index variable to keep track of your counting. When we've gone through this code five times, stop looping and move on." Notice that every time the loop goes around (including the first time through), Index equal 1, the second time through it equals 2, and so on up to 5. It's important to note that after the loop is finished, the value of the Index variable will be 6, one number higher than the highest value in our For statement. This occurs because the Index variable is incremented at the end of the loop, after which the For statement tests the value of Index to see if it is necessary to loop again.

It's difficult to express the real-world usefulness of the For...Next loop without opening a can of worms on a lot of other subjects, but keep in mind that it is often used to traverse some sort of finite piece of data, such as a word, or a text file. For example, the word "elephant" has exactly eight letters. If you first calculate the number of letters in the word "elephant", you could use that number to drive a For...Next loop. Below is a simple example that uses the VBScript Len ( ) function to calculate the length of the word "elephant." Inside the loop, it uses the Mid ( ) function to pull one letter of the word "elephant" at a time.

Dim Index
Dim WordLength
WordLength = Len("elephant")
For Index = 1 to WordLength
MsgBox Mid("elephant", Index, 1)
Next
MsgBox "elephant"

First