DO Until LOOP EXCEL VBA

The Do Until loop is a useful tool in Excel VBA used to repeat a set of steps until the statement is FALSE. When the statement is FALSE we want the loop to stop and the loop naturally comes to an end. So in phrasing the loop the condition is set at the end of the loop. The Do Until Loops condition is then checked with each iteration of the loop and a decision is made if the loop is true or not.

It is the opposite of the Do Until Loop in VBA - where the true condition is where the code stops.

The following are some examples of Do Loops in a practical settings:

Sub LoopUntil()
Dim i As Integer
i = 1

Do Until i = 10
Range("A" & i) = i
i = i + 1
Loop

End Sub

The above loop will place the following numbers in Column A.

Loop Until
 

 The above is the iteration from 1 to 9. It is what the loop was asked to do. Produce a number from 1 to 9.

The i = i + 1 is the heart of the iteration. It allows the loop to increment 1 cell each time.



The following is another example of how to use the Do Until Looping construct. In this Do Until Looping example the above cells in column A will be doubled in column B and the code will only run while the cells in column A are not blank. In this example, the IsEmpty function is evoked with a NOT statement, which says run the procedure while the cells are NOT EMPTY.

Sub LoopUntil1()
Dim i As Integer
i = 1

Do Until IsEmpty(Cells(i, 1))
Range("A" & i) = i
Range("B" & i) = Cells(i, 1) * 2
i = i + 1
Loop

End Sub

The following is how the cells in column B will look after the VBA code has run. The cells in Column A from the first procedure are doubled in value.

Loop Until Excel VBA
 


The above is an example of how the code might look with the numbers doubling.