Excel 2019

Do While Loop

Sometimes, we don’t know exactly how many times we need to perform an operation, but we do know conditions under which we want to perform the processing. In this situation, we can use a Do While Loop. The Do While Loop executes as long as a specified condition is met. When the loop ends, the code below the loop block then executes.

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 While...Loop

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

Do...While Loop

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:

Do While Loop Comparison

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:

Display Input Box inside the loop

Advertisement:
Advertisement: