我需要關於協方差計算的幫助/指導。我寫了下面的程序來計算10年股票數據的協方差。問題是我收到一個錯誤,指出下標超出範圍。我打電話的功能的方式是使用VBA計算協方差矩陣
CalcCovarAll firstColPick:= 17,SecColPick:= 17,ColPrint:= 42
'firstColPick是第一列的地址挑
' secColPick是地址的第二列選擇
'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
我也嘗試刪除for循環,看看它是否計算covar或不,這並沒有給我任何錯誤,實際上打印#DIV/0! – 2013-03-20 14:30:26
我認爲你必須檢查你傳遞給sub = ie的參數。確保你的行/列以1開頭而不是0. – 2013-03-20 14:37:03
也檢查整數的變量,它們的最大值約爲32000 – 2013-03-20 15:05:10