Excel VBA Lesson 14: Mastering the For...Next Loop in Excel VBA
Continue learning classic Excel VBA with the same shared lesson template and cleaner visual style.
14.1 Understanding For...Next Loops
In lesson 12, we learned about decision-making using If...Then...Else structures. Another fundamental programming concept is looping, which allows you to repeat code execution until a condition is met. Excel VBA offers two main types of loops:
- For...Next Loop - Executes a block of code a specific number of times (covered in this lesson)
- Do...Loop - Repeats while or until a condition is met (covered in the next lesson)
14.2 For...Next Loop Syntax
The basic structure of a For...Next loop is:
For counter = startNumber To endNumber [Step increment]
' One or more statements to execute
Next [counter]
Parameters:
- counter: A numeric variable that tracks the current iteration
- startNumber: The initial value of the counter
- endNumber: The value at which the loop stops
- Step increment (optional): The amount to increment the counter each iteration (default is 1)
Note: You can use negative Step values to count downwards, or Step values greater than 1 to skip iterations.
14.3 Practical Examples
Example 14.1: Basic For...Next Loop
This simple example demonstrates how to fill cells in a column with sequential numbers:
Private Sub CommandButton1_Click()
Dim i As Integer
For i = 1 To 10
Cells(i, 1).Value = i
Next
End Sub
How it works:
- When you click the command button, the macro starts executing
- It declares an integer variable
ias the loop counter - The loop runs from 1 to 10 (inclusive)
- Each iteration writes the current value of
ito column A (column index 1), in the row corresponding to the current iteration - The result is numbers 1 through 10 in cells A1 through A10
Example 14.2: Nested For...Next Loops
This example shows how to use nested loops to work with two-dimensional ranges:
Private Sub CommandButton1_Click()
Dim i As Integer, j As Integer
For i = 1 To 10
For j = 1 To 5
Cells(i, j).Value = i + j
Next j
Next i
End Sub
Key points about this example:
- Uses two counters:
ifor rows andjfor columns - The outer loop (
i) runs from 1 to 10 (rows) - The inner loop (
j) runs from 1 to 5 (columns) for each row - Each cell gets the sum of its row and column numbers
- Demonstrates how to work with two-dimensional data structures
Example 14.3: Using Step Value
This example shows how to use the Step keyword to change the increment value:
Private Sub StepExample()
Dim i As Integer
' Count from 0 to 100 by 10s
For i = 0 To 100 Step 10
Debug.Print i
Next i
' Count down from 10 to 1
For i = 10 To 1 Step -1
Debug.Print i
Next i
End Sub
Example 14.4: Practical Application - Formatting a Range
This example demonstrates a real-world application of For...Next loops to format a range of cells based on their values:
Sub FormatRange()
Dim rng As Range
Dim cell As Range
Dim i As Integer
' Set the range to format (A1:A20)
Set rng = Range("A1:A20")
' Fill the range with random numbers first
For i = 1 To 20
Cells(i, 1).Value = Int(Rnd() * 100)
Next i
' Format cells based on their values
For Each cell In rng
If cell.Value > 75 Then
cell.Interior.Color = RGB(0, 255, 0) ' Green for high values
ElseIf cell.Value > 50 Then
cell.Interior.Color = RGB(255, 255, 0) ' Yellow for medium values
Else
cell.Interior.Color = RGB(255, 0, 0) ' Red for low values
End If
Next cell
End Sub
14.4 Best Practices for For...Next Loops
Common Mistakes to Avoid
14.5 Performance Considerations
When working with large datasets, keep these performance tips in mind:
- Minimize interactions with the worksheet - Read data into an array first if you need to process many cells
- Turn off screen updating during long operations with
Application.ScreenUpdating = False - Use Long instead of Integer for counters when dealing with large numbers (Excel rows exceed Integer capacity)
- Consider alternative approaches like worksheet functions for simple operations on large ranges
Summary
✅ In This Lesson, You Learned:
Exercise: Practice What You've Learned
Try these exercises to reinforce your understanding:
- Write a macro that fills a 10x10 grid with multiplication table values
- Create a loop that highlights every third row in a selected range
- Write a procedure that uses a For...Next loop to reverse the order of values in a column
🔗 Related Resources