- Back to Home »
- VBA »
- [VBA] Loop_process
Friday, November 29, 2019
Option Explicit
'Note: Can use "Exit Do, Exit For to exit For loop and Do loop
Sub ForEach_loop()
'fruits is an array
Dim fruits() As Variant
Dim Item As Variant
ReDim Preserve fruits(3)
fruits = Array("apple", "orange", "cherries")
'iterating using For each loop.
For Each Item In fruits
Debug.Print Item
' Exit For
Next
End Sub
Private Sub For_loop()
Dim a As Integer, i As Integer
a = 10
For i = 0 To a Step 2
Debug.Print "The value is i is : " & i
' Exit For
Next
End Sub
Private Sub While_loop()
Dim Counter As Integer
Counter = 10
While Counter < 15 ' Test value of Counter.
Counter = Counter + 1 ' Increment Counter.
Debug.Print "The Current Value of the Counter is : " & Counter
Wend ' While loop exits if Counter Value becomes 15.
End Sub
Private Sub DoWhile_loop()
Dim i As Integer
Do While i < 5
i = i + 1
Debug.Print "The value of i is : " & i
'Exit Do
Loop
End Sub
Private Sub DoUntil_loop()
Dim i As Integer
i = 10
Do Until i > 15 'Condition is False.Hence loop will be executed
i = i + 1
Debug.Print ("The value of i is : " & i)
'Exit Do
Loop
End Sub