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:
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:
Note: You can use negative Step values to count downwards, or Step values greater than 1 to skip iterations.
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:
i
as the loop counteri
to column A (column index 1), in the row corresponding to the current iterationThis 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:
i
for rows and j
for columnsi
) runs from 1 to 10 (rows)j
) runs from 1 to 5 (columns) for each rowThis 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
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
When working with large datasets, keep these performance tips in mind:
Application.ScreenUpdating = False
Try these exercises to reinforce your understanding:
Copyright ® 2008- Dr. Liew Voon Kiong . All rights reserved [Privacy Policy]
Contact: Facebook Page