简体   繁体   中英

Why does this VBA code give me an Object Required error?

I have the following code in an Excel macro:

Dim cellRange As range
Dim cell As range
Dim cellFormula As String
Dim yearCells As New Collection

For Each cellRange In ranges
    For Each cell In cellRange.Cells
        cellFormula = GetCellFormula(cell)
        If (cellFormula = formulaYears) Then
            yearCells.Add (cell)
        End If
    Next
Next

Where ranges is a Collection object holding many Range objects.

When I run the code, I get an "Object required" error on the line For Each cellRange In ranges . Why is this? After all, cellRange is declared as an object, ie Dim cellRange As range . If I convert the code to a For loop, I have the same error on a line:

Set cellRange = ranges(i)

BTW, my VBA IDE insists on range always having a lower case initial letter. When I type Range the editor "corrects" it to range . Yet other code using range objects works fine.

The answer lays in the way you populate your collection I'm sure. For example see the following:

Sub Test()

Dim ranges As New Collection
Dim rng1 As Range, rng2 As Range, rng3 As Range
Dim cellRange As Range, cell As Range

Set rng1 = Range("A1:A3")
Set rng2 = Range("B1:B3")
Set rng3 = Range("C1:C3")

ranges.Add rng1
ranges.Add rng2
ranges.Add rng3

For Each cellRange In ranges
    Debug.Print cellRange.Address
    For Each cell In cellRange
        Debug.Print cell.Address
    Next cell
Next

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM