获取动态范围VBA的长度

时间:2017-06-26 23:20:36

标签: vba excel-vba variable-length excel

我需要根据初始单元格选择存储动态范围的长度,然后选择向下到列的末尾。这里'我现在在哪里

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

当我运行代码并进入第34行时,设置range_prop = Range(Selection,Selection.End(xlDown))。选择"我收到了错误"运行时错误''所需的对象"

如何存储动态范围,然后将其高度或宽度存储为整数?任何帮助将不胜感激!!

2 个答案:

答案 0 :(得分:1)

您无法创建范围变量=选择,您可能只想要范围:

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

答案 1 :(得分:1)

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