Syntax
A Do While loop have two syntax:
- Do While…Loop (It has condition at the top)
- Do…While Loop (It has condition at the bottom)
Do While…Loop
The Do While...Loop
test the condition at the start of the loop, before executing any of the statements
contained inside it. So, if the condition test failed, not a single statement could execute inside the loop.
Do [While condition] [statements] [Exit Do] [statements] Loop
Example
Press Alt + F11
to open Visual Basic Editor (VBE) and write the following code in ThisWorkbook's
code editor:
Sub do_while() Dim i As Integer i = 1 Do While i < 5 Debug.Print i i = i + 1 Loop End Sub
The above example displays 1, 2, 3 and 4 on Immediate window.
Do…Loop While:
The Do...Loop While
test a condition at the end of the loop, after executing any of the statements
contained inside it. So the Do...Loop While
loop will execute statements
at least one time regardless of the condition.
Do [ statements ] [ Exit Do ] [ statements ] Loop [While condition]
Example
Write the following example code in ThisWorkbook's
code editor:
Sub do_while() Dim i As Integer i = 1 Do Debug.Print i i = i + 1 Loop While i < 5 End Sub
You can see that the both example displays the same result. But if you edit the code and change the variable i
value to 5
. The first example will not print anything on Immediate window as the condition not met but the second example will print the 5:
Exit Do
to Terminate or Exit Form the Loop
You can use Exit Do
statement if you want to exit the loop prematurely (without waiting until the condition turns False), for example the following example exits from the loop when the value of i
variable become 2
:
Sub do_while() Dim i As Integer i = 1 Do While i < 5 Debug.Print i If i = 2 Then Exit Do i = i + 1 Loop End Sub
Display input box using Do While…Loop
In this example you will find out how to continuously display an input box until the user enters the correct keyword:
Sub do_while() Dim name As String name = "" Do While name <> "brainbell" name = InputBox("What is my website name?") Loop MsgBox ("Yes!") End Sub
You’ll continuously see the following input box until you enters the brainbell
in the box: