Search
Close this search box.

VBA For Loop


The For...Next loop is a fundamental control flow structure in VBA that allows you to repeat a block of code a specific number of times. It’s particularly useful for iterating over a range of values or performing repetitive tasks.

The For step is executed first. This step allows you to initialize any loop control variables and increment the step counter variable.

Secondly, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and the flow of control jumps to the next statement, just after the For Loop.

After the body of the For loop executes, the flow of control jumps to the next statement. This statement allows you to update any loop control variables. It is updated based on the step counter value.

The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the For Loop terminates.

Explanation:

  1. Initialization: The counter variable is initialized with the startValue.
  2. Condition Check: The loop continues as long as the counter is less than or equal to the endValue.
  3. Code Execution: The code within the loop is executed.
  4. Increment/Decrement: The counter is incremented or decremented by the stepValue (default is 1).
  5. Loop Continuation: The process repeats from step 2.

Syntax:

For counter = startValue To endValue [Step stepValue]
       ‘ Code to be executed
Next counter

Example: Summing Numbers from 1 to 10

				
					Sub SumNumbers()
    Dim sum As Integer
    Dim i As Integer

    sum = 0

    For i = 1 To 10
        sum = sum + i
    Next i

    MsgBox "The sum of numbers from 1 to 10 is: " & sum
End Subgreater than 5"
    End If
End Sub
				
			

Key Points:

  • The Step value can be positive or negative to control the increment or decrement of the counter.
  • You can omit the Step value if you want to increment by 1.
  • The loop will continue until the counter exceeds the endValue.
  • You can use the Exit For statement to exit the loop prematurely.

Example with Step

				
					Sub PrintEvenNumbers()
    Dim i As Integer

    For i = 2 To 20 Step 2
        MsgBox i
    Next i
End Sub
				
			

This code will print even numbers from 2 to 20, incrementing by 2 in each iteration.