Home » excel » excel – Looping through rows of Selection | Range vs Rows

excel – Looping through rows of Selection | Range vs Rows

Posted by: admin April 23, 2020 Leave a comment

Questions:

I’ve got a class Portal with a

Public Function Init(Rng As Range) As Portal

Which processes the first 2 cells of the Rng range, using Rng.Item(1) and Rng.Item(2). This works fine for the first row of a selection:

Sub ProcessPortal()
    Dim mPortal As Portal

    Set mPortal = New Portal
    With mPortal
        .Init Selection
    End With

End Sub

But it fails when I want to loop through the rest of the rows:

Sub ProcessPortal()
    Dim mPortal As Portal
    Dim a As Range, b As Range

    Set a = Selection
    For Each b In a.Rows
        Set mPortal = New Portal
        With mPortal
            .Init b
        End With
    Next b
End Sub

b is a Range, just like Selection, right? Why do I get a type mismatch on .Init b?

How to&Answers:

If you are trying to access cells, use the Cells property of the Range object, rather than the Item property, i.e. use Cells(1) and Cells(2) in your Init procedure.

The first Item of an entire row is the row itself, as can be seen by:

Debug.Print Rows(1).Item(1).Address

which will return $1:$1 while

Debug.Print Rows(1).Cells(1).Address

will return $A$1.