Excel

Do Until Loop

A Do Until...Loop is similar to a Do While...Loop. The difference is how the condition works. This loop executes an action while the condition is False, and repeats the action until the condition becomes True. So, this is the opposite of the way that the condition works in a Do While...Loop.

Syntax

Do [Until condition]
 [statements]
 [Exit Do]
 [statements]
Loop

The Do Until...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.

Example

Press Alt + F11 to open Visual Basic Editor (VBE) and write the following code in ThisWorkbook‘s code editor:

Sub do_until()
 Dim i As Integer
 i = 1
 Do Until i > 5
  Debug.Print i
  i = i + 1
 Loop
End Sub

The above example displays 1, 2, 3, 4 and 5 on Immediate window.

Do…Loop Until

The Do...Loop Until test a condition at the end of the loop, after executing any of the statements contained inside it. So the Do...Loop Until must execute statements at least one time regardless of the condition.

Do
 [statements]
 [Exit Do]
 [statements]
Loop [Until condition]

Example

Sub do_until()
 Dim i As Integer
 i = 1
 Do
  Debug.Print i
  i = i + 1
 Loop Until i > 5
End Sub

The above example displays 1, 2, 3, 4 and 5 on Immediate window. We already learned that the Do...Loop Until must execute statements at least one time regardless of the condition, so if you change the the value of i to 100 it will print 100 on the Immediate window even the condition not met:

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_until()
 Dim i As Integer
 i = 1
 Do Until i > 5
  Debug.Print i
  If i = 2 Then Exit Do
  i = i + 1
 Loop
End Sub