vba - 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 中的矩阵一样,但它不起作用。
如何将函数中的数组返回到电子表格中?我做错了什么以至于上面的代码不起作用?
谢谢您的帮助!
解决方案
使用变体返回数组
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
推荐阅读
- php - 如果页面被访问,如何重定向到另一个页面,但如果页面包含(PHP)
- sympy - 尝试在 Debian 上安装 sympy
- html - 如何使用 jquery 将 html 数据加载到最近的 tr
- python-3.x - 我遵循此示例,但结果显示“进程以退出代码 0 完成”
- python - Python 将多个数据框合并到一个图中
- laravel - Laravel Livewire 队列不允许序列化
- c++ - 如何有效地计算变体向量上的函数?
- python - 如何将库存添加到当前脚本
- c++ - 使用唯一指针的 Vector 类的 C++ 下标运算符 []
- python - 转置部分数据框 Python