VBScript Loop Statements
- Previous Page VB Conditional Statements
- Next Page Summary of VB Tutorial
Example
- For..next loop
- This example demonstrates how to write a simple For....Next loop.
- Loop to output HTML headings
- This example demonstrates how to loop to generate 6 HTML headings.
- For..each loop
- This example demonstrates how to write a simple For...Each loop.
- Do...While loop
- This example demonstrates how to write a simple Do...While loop.
Looping statements
Frequently, when writing code, we want to execute a block of code several times. We can use loop statements in the code to accomplish this task.
In VBScript, we can use four loop statements:
- For...Next statement
- Run a block of statements a specified number of times
- For Each...Next statement
- Run a block of statements for each item in a collection or each element in an array.
- Do...Loop Statement
- Run the loop when the condition is true or until the condition is true.
- While...Wend Statement
- Do not use this statement - please use the Do...Loop statement instead.
For...Next Loop
If you have determined the number of times you need to repeat the code, you can use the For...Next statement to run this code.
We can use a counter variable that will increment or decrement with each loop iteration, for example:
For i=1 to 10 some code Next
The For statement specifies the count variable and its starting and ending values.
The Next statement will increment the variable i by 1 as the step value.
Step Keyword
By using the Step keyword, we can specify the incrementing or decrementing step value of the count variable.
In the following example, the incrementing step value of the count variable i is 2 for each loop iteration.
For i=2 To 10 Step 2 some code Next
If you want to decrement the count variable, you must use a negative step value. And you need to specify an ending value less than the starting value.
In the following example, the decrementing step value of the count variable i is 2 for each loop iteration.
For i=10 To 2 Step -2 some code Next
Exit For...Next
You can use the Exit keyword to exit the For...Next statement.
- Previous Page VB Conditional Statements
- Next Page Summary of VB Tutorial