0

我需要协方差计算的帮助/指导。我编写了以下程序来计算 10 年股票数据的协方差。问题是我收到一个错误,指出下标超出范围。我调用函数的方式是

CalcCovarAll firstColPick:=17, SecColPick:=17, ColPrint:=42

'firstColPick 是第一列pick的地址

'secColPick 是第二列pick的地址

'colPrint 是将输出打印到单元格的特定列上。

任何快速帮助都会非常有帮助。我认为我没有正确实现该功能

Sub CalcCovarAll(ByVal firstColPick As Integer, ByVal SecColPick As Integer, ByVal   ColPrint As Integer)
Dim secondPick As Range
Dim secondValue As Variant
Dim firstPick As Range
Dim firstValue As Variant
Dim wksSheet As Worksheet

Dim rowPrint As Range
Dim cvaluePrint As Variant

Dim Row As Integer
Dim col As Integer

'setting up the active worksheet
Set wksSheet = Workbooks("VaR_cw2 (2).xlsm").Worksheets("Sheet1")
'setting up the pickup of first column
Set firstPick = Range(Cells(4, firstColPick), Cells(2873 + 1, firstColPick))
firstValue = firstPick.Value

'setting up pickup of second column
Set secondPick = Range(Cells(4, SecColPick), Cells(2873 + 1, SecColPick))
 secondValue = secondPick.Value
'setting up column printing
Set rowPrint = Range(Cells(5, ColPrint), Cells(2873 + 1, ColPrint))
cvaluePrint = rowPrint.Value

 For Row = LBound(secondValue) To UBound(secondValue) - 1
    cvaluePrint(Row + 1, 1) = Application.Covar(firstValue, secondValue)
Next Row

rowPrint = cvaluePrint
End Sub
4

3 回答 3

0

rowPrint 从第 5 行开始,而 secondPick 从第 4 行开始。这意味着 cvaluePrint 包含的项目小于 secondValue。

cvaluePrint(1 到 2870)(5 到 2874 - VBA 中的所有数组都从 1 开始,而不是从 5 开始)

secondValue(1 到 2871)(4 到 2874 - VBA 中的所有数组都从 1 开始,而不是从 4 开始)

当您执行 Row 循环时,它从 1 变为 2870,但是当您键入 cvaluePrint(Row + 1, 1) 时,您调用的是从 2 到 2871。最后一行超出范围。使用 cvaluePrint(Row, 1)

于 2013-03-20T16:44:26.950 回答
0

如果您在下面的行中遇到错误,请确保文件名正确并且该文件存在于您的硬盘驱动器上并且已打开。

Set wksSheet = Workbooks("VaR_cw2 (2).xlsm").Worksheets("Sheet1")

在代码顶部使用Option Base 1并更改以下行

For Row = LBound(secondValue) To UBound(secondValue) 
    cvaluePrint(Row + 1, 1) = Application.Covar(firstValue, secondValue)
Next Row

还要确保您的输入变量大于 0。

今后,当您针对任何错误发布任何问题时,请同时指定行号。如果可能,截图。它将帮助您的查询更快地解决。

于 2013-03-20T18:55:21.323 回答
0

改变

cvaluePrint(Row + 1, 1) = Application.Covar(firstValue, secondValue)

cvaluePrint(Row, 1) = Application.Covar(firstValue, secondValue)

因为UBound(cvaluePrint) = 2870, 所以何时Row = 2870,超过了 for 循环最后一次迭代中Row + 1变体的上限。cvaluePrint

于 2013-07-04T10:53:57.663 回答