动态变量赋值VBA

时间:2017-07-07 16:21:36

标签: excel vba

好的,所以我一直在努力弄清楚我的变量“aveCellAdrs”&的分配问题是什么。 'Q'。每个都有错误:对象'Global_'的方法'Range'失败。

我想要的变量'q'和& “aveCellAdrs”要做的是指动态变量'k'(每次循环经过k时k都会改变),然后从中得到它们的新范围。

Heres是我的代码:

             Dim i As Integer
             Dim j As Integer
             Dim k As Range
             Dim q As Range
             Dim tableRange2 As Range
             Dim total As Double
             Dim table2average As Double
             Dim aveCellAdrs As Range


For i = 1 To 20
    Set k = Range("B73").End(xlUp).Offset(i, 0) 'This finds the top-most cell as a starting point
            Set aveCellAdrs = Range(k).End(xlToRight)  'Used to enter the average found in the loops below to the correct cell
                 Set q = Range(k).End(xlToRight).Offset(0, -1)  'This finds the right-most cell in the row
                      Set table2Range2 = Range(k, q)  'Identifying the dynamic range to which we will calculate each rows' average

希望这是有道理的。以下是代码块的附加屏幕截图:

enter image description here

1 个答案:

答案 0 :(得分:2)

braX是正确的,在VBA范围内是一个对象,而不是数据类型。当您输入:

Set table2Range2 = Range(k, q) 

我认为您尝试做的是将范围的最左侧和最右侧限制传递到range()以设置table2Range2的范围。如果是这种情况,您希望传递单元格地址(即B2:E2),这是range()期望接收的内容。您在上面的代码中实际执行的操作是尝试传递整个范围对象,这会导致range()抛出错误。

这就是我要做的事情:首先将一个范围设置为参考点,创建一些字符串变量以将单元格地址保存在您尝试创建的范围的角落。将其构建为字符串并将其传递给range()以针对循环的每次迭代动态设置表范围。设置范围后,可以使用.address方法获取单元格地址。见下文:

Dim i As Integer
Dim startingPoint As Range
Dim rngStart As String
Dim rngEnd As String
Dim tableRange As Range



For i = 1 To 20
    Set startingPoint = Range("B73").End(xlUp).Offset(i, 0)
    rngStart = startingPoint.Address 'This finds the top-most cell as a starting point
    rngEnd = startingPoint.End(xlToRight).Offset(0, -1).Address 'This finds the right-most cell in the row
    Set tableRange = Range(rngStart & ":" & rngEnd)  'Identifying the dynamic range to which we will calculate each rows' average
Next