Do and For loops provide use with several possible tools to use for looping in Visual Basic.
The Do loop is used when you do not know how many times you will need to execute a block of code. It is used when you will execute the same block of code repeatedly until something changes to indicate you are done. The Do loop is controlled by a condition.
There are several forms to the Do loop control structure. The difference between the forms of the Do loops is when the condition is tested and whether you will execute the conditional block of code as long as the condition is true OR as long as it is false.
Do While condition
:
Statements to execute while condition is True
:
Loop
:
:
Do Until condition
:
Statements to execute while condition is False
:
Loop
:
:
Do
:
Statements to execute while condition is True
:
Loop While condition
:
:
Do
:
Statements to execute while condition is False
:
Loop Until condition
:
:
The position of the condition (at the top or at the bottom of the loop) determines the minimum number of times the statements inside the loop will be executed.
While - The instructions inside loop will be executed as
long as the condition is True.
Until - The instructions inside loop will be executed as long
as the condition is False.
The following loops result in the exact same output
intCount = 0
Do While intCount < > 3
intCount = intCount + 1
MsgBox(intCount)
Loop
intCount = 0
Do Until intCount = 3
intCount = intCount + 1
MsgBox(intCount)
Loop
In all cases after the loop has been satisfied execution continues with the
next instruction after the Loop command.
Terminating a loop
Something must happen inside the loop so that the result of the condition
changes. You must be careful not to code impossible or unreasonable loops.
Dim intCount
As Integer
intCount = 1
Do Until intCount = 100
MsgBox(intCount)
intCount += 2
Loop
Do
intCount += 2
intCount -= 2
Loop
Do Loops are suitable when you do not know the number of
times to repeat an action (indeterminate loop).