Nesting Control Structures

As the preceding example demonstrates, you can place control structures inside other control structures (for instance, an If...Then block within a For Each...Next loop within another If...Then block, and so on). A control structure placed inside another control structure is said to be nested.

The following example searches the range of cells you specify with an argument and counts the number of cells matching the value you specify.


Function CountValues(rangeToSearch, searchValue)
    If TypeName(rangeToSearch) <> "Range" Then
        MsgBox "You can search only a range of cells."
    Else
        For Each c in rangeToSearch.cells
            If c.Value = searchValue Then
                counter = counter + 1
            End If
        Next c
    End If
    CountValues = counter
End Function

Notice that the first End If statement closes the inner If...Then block and that the last End If statement closes the outer If...Then block. Likewise, in nested For...Next and For Each...Next loops, the Next statements automatically apply to the nearest prior For or For Each statement. Nested Do...Loop structures work in a similar fashion, with the innermost Loop statement matching the innermost Do statement.