获取动态范围的长度 VBA

Get length of dynamic range VBA

我需要存储基于初始单元格选择的动态范围的长度,然后向下选择到列的末尾。这里是我现在所在的地方

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

当我 运行 代码并到达该行时:

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

我收到错误:

Run-time error '424': Object required

如何存储动态范围,然后将其高度或宽度存储为整数?

您不能使范围变量 = a select,您可能只需要范围:

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

然后您可以对变量使用 .rows.count 和 .columns.count 来获取大小:range_prop.rows.count

您确定要使用 .end(xldown) 吗?它只会转到第一个空格,如果有空格则不会一直转到整个路径。

我在这里为您整理了一些代码:

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
Set range_prop = Range(Selection, Selection.End(xlDown)).Select
number_prop_components = range_prop.Height
MsgBox (range_prop.Height)

应该是:

Set range_prop = Range(Selection, Selection.End(xlDown))
number_prop_components = range_prop.Rows.Count
range_prop.Select
MsgBox number_prop_components

1- 当你在末尾添加 .Select 时,你正在调用一个不返回任何内容的子程序,所以你不能分配结果。

2-范围的高度通过其行数获得,使用myRange.Rows.count

3- 不要在子例程参数周围放置括号,但仅在调用函数返回某些内容时才使用。

4- 通常避免使用 VBA 中的选择。阅读 How to avoid using Select in Excel VBA macros