在VBA中访问LinEst输出

时间:2017-01-18 17:07:03

标签: excel vba excel-vba

我想使用LinEst中的系数,但LinEst返回一个数组。访问数组输出部分的最佳方法是什么?数组的各个数据类型是什么?

1 个答案:

答案 0 :(得分:0)

此解决方案可能会对某人有所帮助,尽管我很欣赏这是一个老问题。

我发现WorksheetFunction.Linest函数针对各种错误返回错误消息Unable to get the LinEst property of the WorksheetFunction class。因此,通过反复试验(很多),我终于找到了这个解决方案:

Sub CalcTrend()
'--------------
' To Determine a simple linear trend of the form y = mx + b

'First declare arrays for x and y data series
Dim x() As Double, y() As Double
' Next declare a variant array for the Linest return values
Dim RtnArray() As Variant
' Also declare simple variable for the individual parameters
Dim m As Double, b As Double, r2 As Double
' Finally declare and index variable for For-Next loop
Dim i As Long

' Both x() and y() arrays MUST be same size
' and assuming the data is in a worksheet in columns x any y then,
'  to populate the arrays, for example
' With Worksheet
'    RowsInDataSet = .Range(.Cells(firstrow, xCol), .Cells(lastRow, xCol)).Rows.Count
' End With
ReDim x(0 To RowsInDataSet)
ReDim y(0 To RowsInDataSet)

For i = 0 To UBound(x)
    x(i) = X_Range.Cells(i + 1, 1) 'Replace X_Range with worksheet range for x series
    y(i) = Y_Range.Cells(i + 1, 1) 'Replace y_Range with worksheet range for y series
Next i

' Now run the Linest function ...
DataArray = WorksheetFunction.LinEst(y, x, , True)
' ... and the results can be found as follows
' Slope
m = DataArray(1, 1)
' Y-intercept
b = DataArray(1, 2)
' Coefficient of determination (how well the data correlates to the line)
r2 = DataArray(3, 1)

End Sub

有关所有“返回数组”值的完整映射,请参见Microsoft docs

此解决方案显示为Sub,以演示如何获取WorksheetFunction返回值。出于实际目的,将带有ByRef参数的Function用于返回数组可能会更有用。