Skip to Content
Course content

3.2 Loops in VBA: For, Do While, For Each.

Loops in VBA allow you to repeat a block of code multiple times, making them essential for automating repetitive tasks. VBA provides various loop structures, each suited for specific scenarios. Here’s a detailed explanation of the most commonly used loops: For, Do While, and For Each.

3.2.1 For Loop

The For loop repeats a block of code a specified number of times. It is useful when the number of iterations is known beforehand.

Syntax:

For counter = startValue To endValue [Step increment]
    ' Code to execute
Next counter
  • counter: The loop variable.
  • startValue: The starting value of the counter.
  • endValue: The ending value of the counter.
  • Step: (Optional) Defines the increment or decrement for the counter. Default is 1.

Example:

Sub ForLoopExample()
    Dim i As Integer
    For i = 1 To 5
        MsgBox "Iteration: " & i
    Next i
End Sub

This code displays a message box for each iteration, from 1 to 5.

Example with Step:

Sub ForLoopStepExample()
    Dim i As Integer
    For i = 10 To 1 Step -2
        MsgBox "Value: " & i
    Next i
End Sub

This loop decrements by 2, starting from 10 and stopping at 1.

3.2.2 Do While Loop

The Do While loop executes a block of code as long as a specified condition remains True. It is useful when the number of iterations is not known in advance.

Syntax:

Do While condition
    ' Code to execute
Loop

Example:

Sub DoWhileExample()
    Dim counter As Integer
    counter = 1
    Do While counter <= 5
        MsgBox "Counter: " & counter
        counter = counter + 1
    Loop
End Sub

This loop continues until counter exceeds 5.

3.2.3 For Each Loop

The For Each loop is specifically designed to iterate through all elements in a collection or array. It is ideal when working with objects, ranges, or collections.

Syntax:

For Each element In collection
    ' Code to execute
Next element

Example:

Sub ForEachExample()
    Dim cell As Range
    For Each cell In Range("A1:A5")
        cell.Value = "Hello"
    Next cell
End Sub

This loop sets the value of each cell in the range A1:A5 to "Hello".

3.2.4 Nested Loops

Loops can be nested within one another for more complex operations, such as processing rows and columns in a worksheet.

Example:

Sub NestedLoopExample()
    Dim i As Integer, j As Integer
    For i = 1 To 3
        For j = 1 To 2
            Cells(i, j).Value = "Row " & i & " Col " & j
        Next j
    Next i
End Sub

This code fills a 3x2 range of cells with labels indicating their row and column.

3.2.5 Breaking Out of Loops

You can use the Exit For or Exit Do statement to exit a loop prematurely.

Example:

Sub ExitForExample()
    Dim i As Integer
    For i = 1 To 10
        If i = 5 Then Exit For
        MsgBox "Iteration: " & i
    Next i
End Sub

This loop stops when i equals 5.

Example with Do While:

Sub ExitDoExample()
    Dim counter As Integer
    counter = 1
    Do While counter <= 10
        If counter = 5 Then Exit Do
        MsgBox "Counter: " & counter
        counter = counter + 1
    Loop
End Sub

3.2.6 Practical Applications of Loops

  1. Populating Data:
    Sub PopulateData()
        Dim i As Integer
        For i = 1 To 10
            Cells(i, 1).Value = "Row " & i
        Next i
    End Sub
    
  2. Summing Values:
    Sub SumValues()
        Dim total As Double, cell As Range
        total = 0
        For Each cell In Range("A1:A10")
            total = total + cell.Value
        Next cell
        MsgBox "Total: " & total
    End Sub
    
  3. Conditional Updates:
    Sub HighlightCells()
        Dim cell As Range
        For Each cell In Range("A1:A10")
            If cell.Value > 50 Then
                cell.Interior.Color = RGB(255, 0, 0)  ' Highlight in red
            End If
        Next cell
    End Sub
    

Summary

  • For Loop: Ideal for iterating a specific number of times.
  • Do While Loop: Suitable for indefinite iterations while a condition remains true.
  • For Each Loop: Perfect for processing items in a collection or array.

By mastering these loops, you can automate repetitive tasks and enhance the efficiency of your VBA projects.

Commenting is not enabled on this course.