Several loops in VBA

» Technical toss » Several loops in VBA

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

 Several Circles in VBA - Geek Park

For digital loop

This kind of loop usually ends after a certain number of executions. If the specified conditions need to be met, it needs to be matched with if
 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

This is the most popular one I use at present. You can directly use a cell range as an array, calculate circularly, or embed a number loop in this 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

This cycle does not specify the number of times, and will end when conditions are met
 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

This cycle does not specify the number of times, and ends when the conditions are met, as above
 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

--End--

Post reply

Your email address will not be disclosed. Required items have been used * tagging