2013-03-20 727 views
0

我需要關於協方差計算的幫助/指導。我寫了下面的程序來計算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 
+0

我也嘗試刪除for循環,看看它是否計算covar或不,這並沒有給我任何錯誤,實際上打印#DIV/0! – 2013-03-20 14:30:26

+0

我認爲你必須檢查你傳遞給sub = ie的參數。確保你的行/列以1開頭而不是0. – 2013-03-20 14:37:03

+0

也檢查整數的變量,它們的最大值約爲32000 – 2013-03-20 15:05:10

回答

0

如果您在下方出現錯誤,請確保文件名是正確的,並且文件存在於您的硬盤驅動器上並且處於打開狀態。

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

使用選項基本1條上的代碼頂部和改變以下線

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

另外,還要確保你的輸入變量是大於0

從此親切指定的行號以及當你發佈任何錯誤的問題。如果可能,截圖這將有助於您的查詢更快解決。

0

rowPrint開始在5號線的功能,同時secondPick開始的行4 這意味着cvaluePrint包含的項目少於secondValue。

cvaluePrint(1到2870)(5至2874 - 在VBA所有數組從1開始,而不是在5)

secondValue(1到2871)(4至2874 - 在VBA所有數組從1開始,而不是4)

當您執行行循環時,它從1到2870But當您鍵入cvaluePrint(行+ 1,1)時,您正在調用從2到2871. 最後一行超出範圍。 使用cvaluePrint(行,1)

0

變化

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

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

由於UBound(cvaluePrint) = 2870,所以當Row = 2870Row + 1超過上限的變異cvaluePrint在for循環的最後迭代。