VBA Step in For Loops
Written by
Reviewed by
This article will explain the Step In functionality in VBA For Loops.
If we consider a For …Next Loop in VBA, the loop is used to repeat the code a set number of times, depending on the value that is specified. The increment each time the loop is run normally increased by the value of 1. The Step functionality enables us to control the increment increase and even instruct the loop to count backwards rather than forwards.
Step Increment
The example below will increment 10 times from 1 until 10.
Sub ForLoop()
Dim i As Integer
For i = 1 To 10
MsgBox i
Next i
End Sub
Sub ForLoop()
Dim i As Integer
For i = 1 To 10 Step 2
MsgBox i
Next i
End Sub
Count in Reverse
We can also use the Step functionality to count in reverse!
Sub ForLoop()
Dim i As Integer
For i = 10 To 1 Step -1
MsgBox i
Next i
End Sub
This loop will start by populating the integer with 10, and then loop through decreasing the value of the integer on each loop by one until it gets to 1.
We can also step in reverse.
Sub ForLoop()
Dim i As Integer
For i = 10 To 1 Step -2
MsgBox i
Next i
End Sub
This is necessary when using a loop to delete rows. If you go top to bottom your code will not run as expected, so you must go bottom to top.