VBA  IV- DO.........LOOP

 

Yesterday I was using the statement  For........Next to execute a repetitive process, today I will show you another looping method know as the Do Loop. There are four ways you can use the Do Loop listed below. Three examples below illustrate three different formats of Do...Loop.

i) Do...........Loop While

(ii) Do until.............Loop

(iii) Do while............Loop

(iv) Do............Loop until

 

Example 1

Private Sub CommandButton1_Click()
Dim counter As Integer
Do
counter = counter + 1
Cells(counter, 1) = counter
Loop While counter < 10

End Sub

Example 2

Private Sub CommandButton1_Click()
Dim counter As Integer
Do Until counter = 10
counter = counter + 1
Cells(counter, 1) = 11 - counter
Loop

End Sub

 

Examle 3

Private Sub CommandButton1_Click()
Dim counter , sum As Integer

'To set the alignment to center
Range("A1:C11").Select
With Selection
.HorizontalAlignment = xlCenter
End With

Cells(1, 1) = "X"
Cells(1, 2) = "Y"
Cells(1, 3) = "X+Y"

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

 

 

 

Example 1

Example 2

Example 3

 

 

 

 

 

 [Back to VBToday]