我知道这是一个非常基本的问题,但我刚刚开始学习vba,并且很难理解如何从价格数组中计算每日回报。我编写的程序在哪里,我无法理解错误。真的感谢有人可以帮助我。这个程序编译没有错误,但函数返回值错误。
Function ch2array(vdata As Variant)
If TypeOf vdata Is Range Then
ch2array = vdata.Value
Else
ch2array = vdata
End If
End Function
Function dailyret(rng)
rng = ch2array(rng)
Dim i, j As Integer
Dim nr, nc As Integer
nc = UBound(rng, 2)
nr = UBound(rng, 1)
Dim gm() As Double
ReDim gm(1 To nr, 1 To nc)
For j = 1 To nc
For i = 1 To nr
gm(i, j) = (Application.Index(rng, j, i) / Application.Index(rng, j, i - 1)) - 1
Next i
Next j
dailyret = gm
End Function
答案 0 :(得分:0)
得到这样的东西:
运行此代码:
Option Explicit
Public Sub FillROR()
Dim rng As Range
Set rng = Range("B2")
Dim i As Long, n As Long
If IsEmpty(rng.Value2) Then
'Missing data
Exit Sub
End If
If IsEmpty(rng.Offset(1, 0).Value2) Then
'Only one price point
Exit Sub
End If
n = rng.End(xlDown).Row - rng.Row + 1
Set rng = rng.Resize(n, 1)
Dim prices As Variant
prices = rng.Value2
Dim ror As Variant
'Ror can only be caclulated for n-1 values
ReDim ror(1 To n - 1, 1 To 1)
For i = 1 To n - 1
ror(i, 1) = prices(i + 1, 1) / prices(i, 1) - 1#
Next i
'Move one column to the right, one row down
rng.Offset(1, 1).Resize(n - 1, 1).Value2 = ror
End Sub