首页 > 解决方案 > VBA:将数组从函数返回到电子表格

问题描述

我正在尝试使用名为“如何使用 VBA 实现市场模型”的书来改进我的 VBA,但我遇到了一些数组问题。特别是,我过去也尝试过但未成功的事情是从函数返回一个数组。

幸运的是,该书的摘录可通过此链接在 Google 图书中找到

Function DailyVar(Quotes!()) As Single()

ReDim t!(UBound(Quotes))

For i = 1 To UBound(t)
    t(i) = (Quotes(i) - Quotes(i - 1)) / Quotes(i - 1)
Next i

DailyVar = t

End Function

上面的代码是我在书中尝试的。但是,如果在电子表格中我在单元格中使用 =DailyVar(some range with numbers),则结果为“#VALUE!”。我尝试在一个范围内运行该函数并使用 CTRL+Shift+Enter 就像 Excel 中的矩阵一样,但它不起作用。

如何将函数中的数组返回到电子表格中?我做错了什么以至于上面的代码不起作用?

谢谢您的帮助!

标签: vba

解决方案


使用变体返回数组

Function DailyVar(Quotes()) As Variant
Dim i As Long
ReDim t(UBound(Quotes))

For i = 1 To UBound(t)
    t(i - 1) = (Quotes(i) - Quotes(i - 1)) / Quotes(i - 1)
Next i

DailyVar = t

End Function

Sub test()
Dim q(3)
q(0) = 3
q(1) = 2
q(2) = 1
Range("b1:d1").Formula = DailyVar(q)
End Sub

编辑 - 使用范围而不是数组

Public Function DailyVar(Q As Range) As Variant
Dim i As Long
Dim Quotes As Variant
Quotes = Q 'fill quotes as array - this is a 2D array even for a single row or column of cells
ReDim t(UBound(Quotes))

For i = 2 To UBound(t)
    t(i - 2) = (Quotes(i, 1) - Quotes(i - 1, 1)) / Quotes(i - 1, 1)
Next i

DailyVar = t
'or if you want them down a column
'DailyVar = Application.WorksheetFunction.Transpose(t)
End Function

推荐阅读