我编写了一个代码,用于计算不断增长的投资组合的方差,并计算投资组合中包含的每个元素的方差5000次。 代码按原样运行,没有问题。
我有点困扰的是,有6个不同的协方差矩阵,代码应该在每个矩阵上运行。
我已经在每个循环中包含了代码以选择和使用6个不同的协方差矩阵,它应该可以工作。
但是我希望将输出(组合的方差)放在6个不同的预定义工作表中,而不是与目前的情况相同。
我的第一个想法是使用数组循环遍历6个新工作表中的每一个,但我不知道如何实现它。
我非常感谢任何指导。
代码如下:
Sub kovariansmatrice()
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
'Dim Var As Long
Dim k, j As Integer
Dim Random As Double
Dim i As Integer
Dim Fifth As Double
Dim varians As Variant
Dim Worksheet As Variant
Dim Worksheets As Variant
Dim outputs As Variant
Worksheets = Array("KVM1D", "KVM2D", "KVM3D", "KVM1M", "KVM2M", "KVM3M")
outputs = Array("Kovar1D", "Kovar2D", "Kovar3D", "Kovar1M", "Kovar2M", "Kovar3M")
For Each Worksheet In Worksheets
For k = 100 To 150 Step 5
Cells(2, 496) = k
For j = 1 To 5000
For i = 1 To 494
Randomize
Random = Rnd()
Worksheets("Kovarians").Cells(3, i).Value = Random
Next i
Fifth = WorksheetFunction.Large(Sheets("Kovarians").Range("A3:BHK3"), k)
Worksheets("Kovarians").Cells(5, 1).Value = Fifth
varians = Application.MMult(Application.MMult(Sheets("Kovarians").Range("A2:BHK2"), Sheets("Kovarians").Range("B11:BHL1581")), Application.Transpose(Sheets("Kovarians").Range("A2:BHK2")))
Worksheets("Kovarians").Cells(5, 3).Value = varians
Calculate
Sheets("Sheet1").Cells(j, k) = Sheets("Kovarians").Cells(5, 3)
Next j
Next k
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
Next Worksheet
End Sub
答案 0 :(得分:1)
请尝试以下
Sub kovariansmatrice()
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
'Dim Var As Long
Dim k, j As Integer
Dim Random As Double
Dim i As Integer
Dim Fifth As Double
Dim varians As Variant
Dim Worksheet As Variant
Dim Worksheets As Variant
Dim outputs As Variant
Worksheets = Array("KVM1D", "KVM2D", "KVM3D", "KVM1M", "KVM2M", "KVM3M")
outputs = Array("Kovar1D", "Kovar2D", "Kovar3D", "Kovar1M", "Kovar2M", "Kovar3M")
Dim indexVal As Integer
indexVal = 0
For Each Worksheet In Worksheets
For k = 100 To 150 Step 5
Cells(2, 496) = k
For j = 1 To 5000
For i = 1 To 494
Randomize
Random = Rnd()
Worksheets(outputs(indexVal)).Cells(3, i).Value = Random
Next i
Fifth = WorksheetFunction.Large(Sheets(outputs(indexVal)).Range("A3:BHK3"), k)
Worksheets(outputs(indexVal)).Cells(5, 1).Value = Fifth
varians = Application.MMult(Application.MMult(Sheets(outputs(indexVal)).Range("A2:BHK2"), Sheets(outputs(indexVal)).Range("B11:BHL1581")), Application.Transpose(Sheets(outputs(indexVal)).Range("A2:BHK2")))
Worksheets(outputs(indexVal)).Cells(5, 3).Value = varians
Calculate
Sheets("Sheet1").Cells(j, k) = Sheets(outputs(indexVal)).Cells(5, 3)
Next j
Next k
indexVal = indexVal + 1
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
Next Worksheet
End Sub