Can an array be used within the LinEst function in VBA?

前端 未结 2 469
轮回少年
轮回少年 2021-01-14 00:38

Basically, rather that selecting a range from cells I have stored values in an array through the use of a loop. What I would ideally like to do is use these arrays as the kn

2条回答
  •  囚心锁ツ
    2021-01-14 01:32

    I achieved this with the below code. Hope it helps.

    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
    

提交回复
热议问题