访问由LinEst函数生成的数组

时间:2016-05-10 22:55:38

标签: excel excel-vba vba

我正在尝试使用以下代码从linEst函数输出所有数据行的R2值:

Sub getdeflection6()
Dim xvalues() As Double, yvalues() As Double, cell As Range
Dim alldata As Range
Dim results As Variant
Dim counter As Integer

ReDim xvalues(0 To 8, 0 To 0)
ReDim yvalues(0 To 8, 0 To 0)
ReDim results(0 To 5, 0 To 6)

xvalues(0, 0) = 0
xvalues(1, 0) = Range("S2").Value
xvalues(2, 0) = Range("P2").Value
xvalues(3, 0) = Range("M2").Value
xvalues(4, 0) = Range("J2").Value
xvalues(5, 0) = Range("G2").Value
xvalues(6, 0) = Range("C2").Value
xvalues(7, 0) = Range("B2").Value

Set alldata = Range("F7", Range("F7").End(xlDown))

counter = 7
For Each cell In alldata

    yvalues(0, 0) = 0
    yvalues(1, 0) = cell.Offset(0, 15).Value
    yvalues(2, 0) = cell.Offset(0, 12).Value
    yvalues(3, 0) = cell.Offset(0, 9).Value
    yvalues(4, 0) = cell.Offset(0, 6).Value
    yvalues(5, 0) = cell.Offset(0, 3).Value
    yvalues(6, 0) = cell.Value
    yvalues(7, 0) = 0

    results = Application.LinEst(yvalues, Application.Power(xvalues, Array(1, 2, 3, 4, 5)), True, True)

    Cells(counter, 23) = results(2, 0)
    counter = counter + 1

Next cell
End Sub

当我尝试访问结果(2,0)数组以获取表示下标超出范围的R2值时,我在最后一行收到错误。我做错了吗?根据我的理解,结果数组将是5行乘6列?

1 个答案:

答案 0 :(得分:1)

当您将结果重新调整为ReDim results(0 To 5, 0 To 6)时,它不会锁定'该变体数组的UBound和{{3}}维度。

此行将结果重置为结果(1到5,1到6)。

results = Application.LinEst(yvalues, Application.Power(xvalues, Array(1, 2, 3, 4, 5)), True, True)

事实上,原始的redim声明根本没有意义。使用新的LBound(结果,1)和LBound(结果,2)从数组中检索所需的值。

Cells(counter, 23) = results(2, 1)

我不确定那里的2。新的LBound(结果,1)为1,可能必须为3。