How to do: "for loop decrement vba"

Below we will find an example of how to decrement loop in vba, or so called reverse looping. It really works the same way as a normal for loop where the step is assigned. Please find the identical results below in the excel prints. However, the latter one started from cell A10 versus the first that started from cell A1.


 

 
Looping to 10 step 1

Sub Loop1 ()
 

 
'Clears any previous content in the sheet.
 
Cells.Clear
 

 
'Steps 1 cell each time and prints it in column A. (1,2,3...10)
 
For i = 1 To 10
 
Cells(i, 1) = i
 
'Range("A"&i), this the same thing.
 
Next i
 

 
End Sub

Reverse or decrement Looping

Sub LoopReverse()
 

 
Cells.Clear
 

 
'Steps -1 each time and prints it in column A.
 
'The result is exactly the same as our first loop.
 
'However, this is printed in the reverse order starting from A10.
 

 
For i = 10 To 1 Step -1
 
'This will print in reverse order.
 
Cells(i, 1) = i
 
Next i
 

 
End Sub

Learn much more about looping in my bigger article here: https://www.pls-fix-thx.com/post/vba-looping-for-each-while

Learn more about VBA here for all my posts: https://www.pls-fix-thx.com/vba

Learn more about Python here for all my posts: https://www.pls-fix-thx.com/python

If you have found this article or website helpful. Please show your support by visiting the shop below.

    660
    0