VBA Step in For Loops

Written by

Mel Jenkins

Reviewed by

Steve Rynearson

Last updated on June 30, 2022

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
If we adjust the code to include a step, each time the loop runs, it will increment by that step.
Sub ForLoop()
  Dim i As Integer
  For i = 1 To 10 Step 2
    MsgBox i
  Next i
End Sub
Therefore rather than getting a message box showing each number from one to ten when the code is run, we will get one showing every second number.

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.

 

vba-free-addin

VBA Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

(No installation required!)

Free Download

Return to VBA Code Examples