Datasheet
Chapter 1: A Quick Introduction to Programming
17
1 to 10, and use the Counter  variable to keep track of your counting. When you’ve gone through this 
loop ten times, stop looping and move on to the next bit of code.” 
 Notice that every time the loop goes around (including the first time through), the 
Counter  variable 
holds the value of the current count. The first time through, 
Counter  equals 1, the second time through 
it equals 2, and so on up to 10. It’s important to note that after the loop is finished, the value of the 
Counter  variable will be 11, one number higher than the highest value in your For  statement. 
The reason for this is that the 
Counter  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. 
 Giving you a meaningful example of how to make use of the 
For...Next  loop isn’t easy because you 
haven’t been exposed to much VBScript just yet, but here’s an example that shows you don’t need to 
know how many times the loop needs to run before you run it. 
  Dim Counter
Dim WordLength
Dim WordBuilder
WordLength = Len(“VBScript is great!”)
For Counter = 1 to WordLength
 MsgBox Mid(“VBScript is great!”, Counter, 1)
 WordBuilder = WordBuilder & Mid(“VBScript is great!”, Counter, 1)
Next
MsgBox WordBuilder
   For example, the phrase “VBScript is great!”  has exactly 18 letter spaces. If you first calculated the 
number of letters in the phrase, you could use that number to drive a 
For...Next  loop. However, this 
code uses the VBScript 
Len()  function to calculate the length of the phrase used. Inside the loop, it uses 
the 
Mid()  function to pull one letter out of the phrase one at a time and display them separately. The 
position of that letter is controlled by the counter variable, while the number of letters extracted is 
defined by the 
length  argument at the end. It also populates the WordBuilder  variable with each loop, 
adding each new letter to the previous letter or letters, rebuilding the phrase. 
 Here’s a variation of the last example: here giving the user the opportunity to type in a word or phrase to use, 
proving that there’s nothing up your sleeve when it comes to knowing how many times to loop the code. 
  Dim Counter
Dim WordLength
Dim InputWord
Dim WordBuilder
InputWord = InputBox (“Type in a word or phrase to use”)
WordLength = Len(InputWord)
For Counter = 1 to WordLength
 MsgBox Mid(InputWord, Counter, 1)
 WordBuilder = WordBuilder & Mid(InputWord, Counter, 1)
Next
MsgBox WordBuilder & “ contains “& WordLength & “ characters.”
c01.indd 17c01.indd 17 8/27/07 7:45:23 PM8/27/07 7:45:23 PM










