可以在VBA中的LinEst函数中使用数组吗?

时间:2014-01-21 19:41:32

标签: arrays vba

基本上,而不是从单元格中选择一个范围,我通过使用循环在数组中存储了值。我理想的做法是将这些数组用作LinEst函数中的已知x和y。

这个目的并不重要,因为我想要做的只是我已编写的代码的一部分。但是,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函数中使用一个数组,但是这些例子通常与我想要做的完全不同。

如果有人可以提供任何帮助,我会非常感激。先感谢您。任何问题随时都可以问。

2 个答案:

答案 0 :(得分: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帮助中另有说明。

答案 1 :(得分: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