Search code examples
vbaexcelvariable-length

Get length of dynamic range VBA


I need to store the length of a dynamic range based on an initial cell selection and then selecting down to the end of the column. Here' where I am at now

Sub Macro1()

Dim number_prop_components As Integer
Dim range_prop As Range

Range("C26").Select
Set range_prop = Range(Selection, Selection.End(xlDown)).Select
number_prop_components = range_prop.Height
MsgBox (range_prop.Height)

End Sub

When I run the code and get to the line:

Set range_prop = Range(Selection, Selection.End(xlDown)).Select

I get the error:

Run-time error '424': Object required

How can I store a dynamic range and then get it's height or width stored as an integer?


Solution

  • You can't make a range variable = a select, you probably want just the range:

    Set range_prop = Range(Selection, Selection.End(xlDown))
    

    You can then use .rows.count and .columns.count against the variable to get the size: range_prop.rows.count

    Are you sure you want to use .end(xldown)? it will only go to the first blank, not the whole way if there is a blank.

    I have cleaned up your code a little for you here:

    Sub Macro1()
        Dim number_prop_components As Long, range_prop As Range
        Set range_prop = Range(Range("C26"), Range("C26").End(xlDown))
        number_prop_components = range_prop.Rows.Count
        MsgBox (number_prop_components)
    End Sub