VBScript
  1. VBScript intro
  2. VBScript basics
  3. VBScript variables
  4. VBScript procedures
  5. VBScript popup boxes
  6. VBScript conditions
  7. VBScript loops
  8. VBScript arrays
  9. VBScript strings
  10. VBScript date & time
  11. VBScript for IE 11
  12. VBScript summary

VBScript loops

Imagine you have to write a program which performs a repetitive task such as counting from 1 to 100. Coding 100 lines to do this task would be mundane. There has to be an easier way, right? This is where loops come into the picture. Loops are specifically designed to perform repetitive tasks with one set of code. Loops save alot of time.

This tutorial focuses on:

The for next loop

The for next loop is used to repeat a task a specific number of times.

Syntax:
for aVariable = numStart to numEnd step aVariableIncrement code to be executed next
Example:
<script type="text/vbscript"> for a = 1 to 10 step 2 document.write(a & " ") next </script>
Output:
1 3 5 7 9

In the above example, the for next loop specifies that a loop should loop 10 times and increment the looping variable by 2 each time. Within the loop body the statement document.write(a & " ") will print the current value of the looping variable through each iteration together with a single space.

The do while loop

The do while loop works differently then the for loop. The for loop repeats a segment of code a specific number of times, while the do while loop repeats a segment of code an unknown number of times.

Syntax:
do while condition code to be executed loop
Example:
<script type="text/javascript"> Dim num num = 0 do while num < 30 num = num + 5 document.write(num & "<br />") loop </script>
Output:
5 10 15 20 25 30

In the above example, a variable named num is given the value 0. The condition in the while loop is that while num is less than 30, 5 should be added to num. Once the value of num is greater than 30, the loop will stop executing. The loop prints the current value of num followed by a line break through each iteration.

© Copyright 2013-2014 Landofcode.com
Terms of use | Privacy policy | Copyright information