2014-01-21 43 views
2

基本上,而不是從單元格中選擇一個範圍,我通過使用循環將值存儲在數組中。我最想做的就是將這些數組用作LinEst函數中已知的x和y。在VBA的LinEst函數中可以使用數組嗎?

這樣做的目的是不重要的,我所要做的僅僅是我已經寫代碼的一部分。然而,Do循環(以及至少第二個)確實需要在那裏,因爲我試圖應用它的代碼需要它們才能起作用。

下面是我試圖編寫的代碼的一個簡單示例。

Sub Test() 

Dim Counter As Long 
Dim Counter_1 As Long 

Dim x As Single 
Dim y As Single 
Dim i As Single 
Dim m As Single 

Dim myArray_1() As Single 
Dim myArray_2() As Single 

ReDim myArray_1(i) 
ReDim myArray_2(i) 

Counter = 2 
Counter_1 = 2 

i = 0 

Cells(1, 4) = "m" 

x = Cells(Counter, 1) 
y = Cells(Counter, 2) 

Do 

Do Until x = 0 

myArray_1(i) = x 
myArray_2(i) = y 

Cells(Counter, 6) = myArray_1(i) 
Cells(Counter, 7) = myArray_2(i) 


i = i + 1 

Counter = Counter + 1 

x = Cells(Counter, 1) 
y = Cells(Counter, 2) 

ReDim Preserve myArray_1(i) 
ReDim Preserve myArray_2(i) 

Loop 

m = WorksheetFunction.LinEst(myArray_2, myArray_1) 

Cells(Counter_1, 4) = m 

Loop 

End Sub 

所以基本上我想LinEst函數使用每個數組作爲已知的y和已知的x's。根據我所做的更改,我會得到不同的錯誤,例如「類型不匹配」或「無法獲取工作表函數類的LinEst屬性」。無論哪種方式,我到目前爲止沒有運氣讓這個工作,它總是錯誤的。從LinEst函數中我只需要漸變'm'。

事情被放入單元格的唯一原因是要確保代碼正在做我所要求的。

從我可以告訴環視互聯網有可能LINEST函數中使用數組,但這些例子通常是什麼,我試圖做的完全不同。

如果任何人都可以提供幫助,我會非常感激。先謝謝你。有任何問題請隨時詢問我(們)。

回答

3

是的,可以這樣做。下面的代碼片段應該幫助你開始:

Dim x() As Variant 
    ReDim x(1 To 3) 
    x(1) = 1 
    x(2) = 2 
    x(3) = 3 

    Dim y() As Variant 
    ReDim y(1 To 3) 
    y(1) = 4 
    y(2) = 5 
    y(3) = 6 

    Dim z() As Variant 
    z = WorksheetFunction.LinEst(x, y) 

該函數返回一個Variant其「盒子」 Variant數組(這將是要麼一維或二維)。其他兩個參數(以上未顯示)是True或False。該功能在Excel幫助中另有詳細說明。

2

我用下面的代碼實現了這個。希望能幫助到你。

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 
+0

非常有幫助!您也可以直接訪問每個係數,因爲LinEst返回一個數組,即LeastSquareCoef(1),LeastSquareCoef(2)等。 – Benjamin

相關問題