VBA Do Until Loop - Javatpoint

next → ← prev VBA Do Until Loop

The Do Until Loop is used when we want to repeat a block of code or a set of statements indefinitely until the condition is True. The condition can be checked either at the start or at the end of the loop.

The Do Until ... Loop Statements check the condition at the start of the loop and The Do ... Loop Until Statements check the condition at the end of the loop.

If the condition is checked at the start of the loop, the block of code does not execute if the condition is met itself initially (and the loop does not run even once). And if the condition is checked at the end, the Loop runs atleast once.

Syntax

Do Until... loop statements

Do Until [Condition] ............... ............... [Block of code] ............... Loop

Flow Diagram

VBA Do Until Loop

Example

In this example, we use Do Until... loop to check the condition at the starting of the loop. The statement inside the loop is executed only if the condition is false. And it exists out of the loop when then the condition is True.

Private Sub Constant_demo_Click() i = 5 Do Until i > 10 i = i + 1 MsgBox ("The value of i is : " & i) Loop End Sub

After executing the code, you will get the output:

The value of i is: 6 The value of i is: 7 The value of i is: 8 The value of i is: 9 The value of i is: 10 The value of i is: 11

Do... Until loop statements

Do...Until loop is used to check the condition at the end of the loop.

Syntax

Do .............. .............. [Block of code] .............. Loop Until [Condition]

Flow Diagram

VBA Do Until Loop

Example

In this example, we use Do...Until loop to check the condition at the end of the loop. The statements inside the loop are executed at least once, even if the condition is true.

Private Sub Constan_demo_Click() i = 5 Do i = i + 1 MsgBox "the value of i is: " & i Loop Until i < 10 End Sub

After executing the code, you will get the following output in a message box.

VBA Do Until Loop

Exit Do Statement

You can exit the Do While or Do Until Loop early, without completing the full cycle, by using the Exit Do statement.

The Exit Do statement will immediately stop the execution of the loop and execute the section of code immediately. In the case of the inner nested level, it will stop and executes the next outer nested level.

You can have multiple numbers of Exit Do statements in a single loop. It is particularly useful in a case where you want to terminate the loop on reaching a particular value or satisfying a specific condition, or in case you want to end an endless loop at a certain point.

For example:

Sub exitDo1() Dim i As Integer Dim iTotal As Integer iTotal = 0 Do While i < 10 iTotal = i + iTotal i = i + 1 If i = ActiveSheet.Range("A1") Then Exit Do End If Loop MsgBox iTotal End Sub

Executes the above code and you will get the following output.

VBA Do Until Loop Next TopicVBA Functions ← prev next →

Từ khóa » Visual Basic Do Until Example