Looping Statements in Visual Basic 6.
0 (VB6)
1. Do While...Loop
Used when: You want to repeat a block of code while a condition is true.
Syntax:
Do While condition
' Code to repeat
Loop
Example:
Dim i As Integer
i=1
Do While i <= 5
MsgBox "Number is " & i
i=i+1
Loop
Note: The condition is checked before the loop runs.
2. Do Until...Loop
Used when: You want to repeat a block of code until a condition becomes true.
Syntax:
Do Until condition
' Code to repeat
Loop
Example:
Dim i As Integer
i=1
Do Until i > 5
MsgBox "Number is " & i
i=i+1
Loop
Note: The loop stops when the condition becomes true.
3. While...Wend
Used when: You want to repeat code while a condition is true. It's an older, simpler loop
form (less flexible).
Syntax:
While condition
' Code to repeat
Wend
Example:
Dim i As Integer
i=1
While i <= 5
MsgBox "Number is " & i
i=i+1
Wend
Limitations:
- You can’t use `Exit While` or include `DoEvents` easily.
- `While...Wend` is mostly replaced by `Do While...Loop` in modern VB coding.
Summary Table
Loop Type Condition Checked Loop Continues Can Use Exit
When Statement?
Do While...Loop Before loop Condition is True Yes
Do Until...Loop Before loop Condition is False Yes
While...Wend Before loop Condition is True No