我是新来的。 :)我试过先搜索,但找不到我正在寻找的东西,所以这里就是。
我的excel工作表中有一组日期和N个资产的T每日回报。我想要做的是根据过去x天所有资产的回报,在每个月的月初创建一个N * N协方差矩阵。
我这里有这个代码用于创建协方差矩阵,但我不知道如何让excel / vba在每个月初自动创建其中的几个。如果有人能帮助我,真棒。 :)
Function VarCovar(Rng As range) As Variant
Dim i As Integer
Dim j As Integer
Dim numcols As Integer
numcols = Rng.Columns.Count
Dim matrix() As Double
ReDim matrix(numcols - 1, numcols - 1)
For i = 1 To numcols
For j = 1 To numcols
matrix(i - 1, j - 1) = Application.WorksheetFunction.Covar(Rng.Columns(i), Rng.Columns(j))
Next j
Next i
VarCovar = matrix
End Function
答案 0 :(得分:1)
试试这个:
Sub VarCovar(rng as Range, target as Range)
Dim i As Integer
Dim j As Integer
Dim numcols As Integer
numcols = Rng.Columns.Count
Dim matrix() As Variant
ReDim matrix(1 to numcols, 1 to numcols)
For i = 1 To numcols
For j = 1 To numcols
matrix(i, j) = Application.WorksheetFunction.Covar(Rng.Columns(i), Rng.Columns(j))
Next j
Next i
Set target = target.Resize(numcols,numcols)
target.Value = matrix
End Sub
现在,当您想要完成此操作时,请使用数据的参考范围(如前所述)调用该函数,并调用显示covar的目标位置的参考范围。