Home » excel » excel – Linest function in vba cannot obtain coefficients for 4th order polynomial

excel – Linest function in vba cannot obtain coefficients for 4th order polynomial

Posted by: admin May 14, 2020 Leave a comment

Questions:

I am having issues with applying the function linest to my code, in order to obtain the best fit polynomials. The issue here is that my code works perfectly when obtaining a 2nd order polynomial regression, but any higher order attempts fail. This is my code:

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)

Note that the program works when i use the following excel formula, but i need to be able to select ranges of variable size to determine the fitting coefficients, so its not an option

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

I finally figured out how to do it through trial and error. All I had to do is add .WorksheetFunction to my code such as this.

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

Answer:

Can you use this pattern but make sure you are working in the right sheet so add the sheet reference in. This worked for me.

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:

Test run