How It Works

The TestLoop procedure begins by declaring an intCounter variable to store the number of times the loop has been iterated.

Sub TestLoop()

'declare variable to store Counter Dim intCounter As Integer

The For...Next statement comes next, with code specifying that the loop should run with intCounter starting at 1 and repeat multiple times until intCounter reaches 5. The Next statement increments the intCounter value by one. When intCounter reaches 5, the Debug.Print statement will execute for the last time and then the loop is exited.

'increment intCounter from 1 to 5 and 'display output in debug window For intCounter = 1 To 5

Debug.Print intCounter Next intCounter

The Do...Loop statement can be used instead of For...Next to accomplish the same purpose. The two types of Do...Loops are Do...While and Do...Until. Do...While may never run any statements if the condition is not initially true, while Do...Until will always run at least once.

The generic syntax for Do...Loop is shown here.

Do [{While | Until} condition]

'statements go here Loop

Or, you can use this syntax: Do

'statements go here Loop [{While | Until} condition]

The following code uses a Do...While statement to accomplish the same result as the For...Next loop described previously.

Do While intCounter <= 5

Debug.Print intCounter intCounter = intCounter + 1 Loop

An example of a Do Until loop is shown here.

Do Until intCounter = 6 Debug.Print intCounter intCounter = intCounter + 1 Loop

If the condition in a Do Until statement is never met, then the loop is known as an infinite loop, which will execute indefinitely.


The While...Wend statement executes repeatedly while a certain condition is met. When the condition is no longer met, the loop terminates. Here is an example:

intCounter = 1 While intCounter <= 5

Debug.Print intCounter intCounter = intCounter + 1 Wend

0 0

Post a comment