多项式“LinEst”VBA调用使用数组而不是范围

我无法检索二阶线函数的系数,并且MsgBox返回一个错误:“types不匹配”。

我期望linest函数给出{0,0,1},因为我在这个例子中使用了平方函数f:x->x²。

Sub RunLinestOld() Dim vectorX() As Double Dim vectorY() As Double Dim theLeastSquareCoef 'redimensionne les vecteurs ReDim vectorX(1 To 4) ReDim vectorY(1 To 4) vectorX(1) = 1 vectorX(2) = 2 vectorX(3) = 3 vectorX(4) = 4 vectorY(1) = 1 vectorY(2) = 4 vectorY(3) = 9 vectorY(4) = 16 'theLeastSquareCoef = Application.LinEst(vectorY, vectorX) theLeastSquareCoef = Application.LinEst(vectorY, Application.Power(vectorX, Array(1, 2))) **MsgBox "K is " & Application.Index(theLeastSquareCoef, 1, 2)** End Sub 

我用下面的代码实现了这一点。 您需要将维度为Nx1的matrix传递给LinEst函数,而不是向量。

 Sub RunLinEst() Dim vectorX() As Double Dim vectorY() As Double Dim theLeastSquareCoef 'you need to define matrix otherwise it doesn't work ReDim vectorX(0 To 4, 0 To 0) ReDim vectorY(0 To 4, 0 To 0) vectorX(0, 0) = 0 vectorX(1, 0) = 1 vectorX(2, 0) = 2 vectorX(3, 0) = 3 vectorX(4, 0) = 4 vectorY(0, 0) = 0 vectorY(1, 0) = 1 vectorY(2, 0) = 4 vectorY(3, 0) = 9 vectorY(4, 0) = 16 theLeastSquareCoef = Application.LinEst(vectorY, Application.Power(vectorX, Array(1, 2))) Range("F4").Value = Application.Index(theLeastSquareCoef, 1) Range("F5").Value = Application.Index(theLeastSquareCoef, 2) Range("F6").Value = Application.Index(theLeastSquareCoef, 3) End Sub 

您需要将linest的结果转换为string

  MsgBox("K is " & CStr(Application.Index(theLeastSquareCoef, 1, 2)))