Do Loops in Excel VBA 365 provide powerful ways to repeat blocks of code while or until certain conditions are met. Unlike For...Next loops that run a set number of times, Do Loops offer more flexibility in controlling program flow.
VBA provides four ways to implement Do Loops, each serving different programming needs:
While vs Until: While continues while a condition is true, Until continues until a condition becomes true.
Condition Placement: When the condition is at the start, the loop may not run at all. When at the end, it runs at least once.
This example demonstrates how to arrange numbers in ascending order using a Do...Loop While structure:
Private Sub CommandButton1_Click() Dim counter As Integer Do counter = counter + 1 Cells(counter, 1) = counter Loop While counter < 10 End Sub
Explanation: This code will:
This example shows a more practical application with multiple columns and calculations:
Private Sub CommandButton1_Click() Dim counter As Integer, sum As Integer 'Formatting the output range Range("A1:C11").Select With Selection .HorizontalAlignment = xlCenter End With 'Setting column headers Cells(1, 1) = "X" Cells(1, 2) = "Y" Cells(1, 3) = "X+Y" 'Main loop with calculations Do While counter < 10 counter = counter + 1 Cells(counter + 1, 1) = counter Cells(counter + 1, 2) = counter * 2 sum = Cells(counter + 1, 1) + Cells(counter + 1, 2) Cells(counter + 1, 3) = sum Loop End Sub
This example demonstrates exiting a loop when a condition becomes true:
Private Sub CommandButton2_Click() Dim userInput As String Do Until userInput = "quit" userInput = InputBox("Enter text (type 'quit' to exit)", "Loop Example") If userInput <> "quit" Then MsgBox "You entered: " & userInput End If Loop End Sub
This example includes basic error handling within a loop:
Private Sub CommandButton3_Click() Dim validEntry As Boolean Dim userValue As Double Do On Error Resume Next userValue = InputBox("Enter a number between 1 and 100", "Number Validation") If Err.Number <> 0 Then MsgBox "Please enter a valid number", vbExclamation Err.Clear ElseIf userValue >= 1 And userValue <= 100 Then validEntry = True Else MsgBox "Number must be between 1 and 100", vbExclamation End If Loop Until validEntry MsgBox "Thank you! Your number is: " & userValue, vbInformation End Sub
Copyright ® 2020 Dr.Liew Voon Kiong . All rights reserved [Privacy Policy]
Contact: Facebook Page