VBA中的线性函数无法获取四阶多项式的系数

时间:2018-08-02 15:43:03

标签: excel vba excel-vba

我在将函数linet应用于我的代码时遇到问题,以便获得最合适的多项式。这里的问题是,当获得二阶多项式回归时,我的代码可以完美地工作,但是任何更高阶的尝试都会失败。这是我的代码:

Dim x_val As Range
Dim y_val As Range
Set x_val = Range(Cells(8, 19), Cells(7 + temperatures.count, 19))
Set y_val = Range(Cells(8, 20), Cells(7 + temperatures.count, 20))

Coefficients = Application.LinEst(y_val, Application.Power(x_val, Array(1, 2, 3, 4)))

.Cells(7, 23) = Coefficients(1) 'This is the line where i get the error "type mismatch"
.Cells(8, 23) = Coefficients(2)
.Cells(9, 23) = Coefficients(3)
.Cells(10, 23) = Coefficients(4)
.Cells(11, 23) = Coefficients(5)

请注意,当我使用以下excel公式时,该程序可以运行,但是我需要能够选择可变大小的范围来确定拟合系数,因此这不是一个选择

Coefficients = Application.Evaluate("=linest(T8:T74,S8:S74^{1,2,3,4})")

2 个答案:

答案 0 :(得分:1)

您可以使用此模式,但请确保您使用的是正确的工作表,因此请添加工作表引用。这对我有用。

Option Explicit
Public Sub TEST()
    Dim x As Range, y As Range
    Set x = Range("T8:T74")
    Set y = Range("S8:S74")

    Dim b As Double, C1 As Double, C2 As Double, C3 As Double, C4 As Double
    b = Evaluate("INDEX(LINEST(" & x.Address & "," & y.Address & "^{1,2,3,4}),1,5)")
    C1 = Evaluate("INDEX(LINEST(" & x.Address & "," & y.Address & "^{1,2,3,4}),1,4)")
    C2 = Evaluate("INDEX(LINEST(" & x.Address & "," & y.Address & "^{1,2,3,4}),1,3)")
    C3 = Evaluate("INDEX(LINEST(" & x.Address & "," & y.Address & "^{1,2,3,4}),1,2)")
    C4 = Evaluate("INDEX(LINEST(" & x.Address & "," & y.Address & "^{1,2,3,4}),1)")

    Debug.Print b, C1, C2, C3, C4
End Sub

试运行:

Test run

答案 1 :(得分:1)

我终于想出了如何通过反复试验来做到这一点。我要做的就是将.WorksheetFunction添加到这样的代码中。

Coefficients = Application.WorksheetFunction.LinEst(y_val, Application.Power(x_val, Array(1, 2, 3, 4)))