Recently, I need a lot of places to use VBA in my work. To be honest, I looked down upon this ancient programming language before, but I found it very fragrant after actual use, so I took notes on some things
For digital loop
Private Sub Constant_demo_Click() Dim a As Integer a = 10 For i=0 To a Step 2 'This is step, default is 1 MsgBox ("The value is i is : " & i) Next End Sub
Array loop
Private Sub Constant_demo_Click() 'fruits is an array. You can also directly extract a cell range as an array Fruits=Array ("apple", "orange", "cherry") Dim fruitnames As Variant 'iterating using For each loop. For Each Item In fruits fruitnames = fruitnames & Item & Chr(10) Next MsgBox fruitnames End Sub
While Wend Loop
Private Sub Constant_demo_Click() Dim Counter : Counter = 10 While Counter < 15 ' Test value of Counter. Counter = Counter + 1 ' Increment Counter. msgbox "The Current Value of the Counter is : " & Counter Wend ' While loop exits if Counter Value becomes 15. End Sub
Do... While Loop
Private Sub Constant_demo_Click() Do While i < 5 i = i + 1 msgbox "The value of i is : " & i Loop End Sub
Exit loop
Exit For Exit Do