从用户定义的函数返回Excel VBA中的数组/矩阵

时间:2017-04-27 22:40:51

标签: excel vba excel-vba

我是Excel VBA的新手,自从我完成任何VBA以来已有5年了。我已经编写了一个UDF来进行基本的回归,但我不能让它输出一个回归值数组。我选择我要输出的范围,然后点击crtl + shift + enter,但它不起作用。我尝试了一些不同的东西,但没有什么可以做的。这是我最近的尝试:

Function REGRESSMEDIAN(x As Range, y As Range) As Double

Dim slope As Double, intercept As Double, count As Integer

count = x.count

Dim lny() As Double, regression() As Double
ReDim lny(1 To count), regression(1 To count)

Dim i As Integer

For i = 1 To count
    lny(i) = Application.WorksheetFunction.Ln(y(i))
Next i


slope = Application.WorksheetFunction.slope(lny, x)
intercept = Application.WorksheetFunction.intercept(lny, x)

Dim j As Integer

For j = 1 To count
    regression(j) = Exp(slope * x(j) + intercept)
Next j

    REGRESSMEDIAN = regression

End Function

1 个答案:

答案 0 :(得分:0)

此测试功能:

Function tester()
    tester = Array("a", "b", "c")
End Function
只要您的3个输出单元格连续而不是列,

将作为UDF 正常工作。如果他们在一个专栏中,那么你只会在所有3个单元格中看到“a”。

enter image description here

如果您尝试将输出放在列中,那么这将起作用:

Function tester()
    tester = Application.Transpose(Array("a", "b", "c"))
End Function

enter image description here