Other Structures in Excel VBA

This section introduces two other loop structures in Excel VBA: For Each...Next and Do loops.

For Each...Next Loop Structure

The For Each...Next loop repeats the same operation on all objects in a collection or all elements in an array. Syntax:

code.vba
For Each var In items
    statements
Next [var]

Runs the loop body for each item in items. var is the iteration variable, and items is the collection of items.

The following example outputs the title of each document in App.Documents in the Immediate Window:

code.vba
Sub Test()
    Dim Document As Object
    For Each Document In App.Documents
        Debug.Print Document.Title
    Next Document
End Sub

In Python, everything is an object, so ordinary for loops can be used to iterate over class objects.

Do Loop Structure

Section 5.3.1 introduced the Do loop in Excel VBA. The Do loop has multiple syntax formats:

Format 1:

code.vba
Do
    statements
Loop

No condition in the loop header/footer; use Exit or GoTo to exit the loop from the body.

Format 2:

code.vba
Do {Until|While} condition
    statements
Loop

Evaluates the condition in the loop header; executes the body if the condition is met.

Format 3:

code.vba
Do
    statements
Loop {Until|While} condition

Evaluates the condition in the loop footer; executes the body at least once before checking.

Note: Until terminates the loop when the condition is met; While executes the body when the condition is met. For the same logic, their conditions are opposite. For example, "loop while intA > 0" can be written as:

Do While intA > 0 ... Loop

Do Until intA <= 0 ... Loop