Referring to a Column within an array

axupaxu
04-23-2008, 06:18 AM
I have data on stock prices in columns b-f, rows 2-251. I then calculate the returns on these prices and store them in an array called vReturns.

Then I want to calculate the covariances between the the stock returns, i.e. the covariances between columns in vReturns and store these in a 5x5 array called vMatrix.
However, unlike with the range.columns property, I am unable to specify a certain column within vReturns. I get "Invalid qualifier". Please advice. Entire code below: The faulty code is marked bold:

Public Function CovarMatrix(Theprices As Range) As Variant
Dim vRow As Integer
Dim vColumn As Integer
Dim vMatrix() As Variant
Dim vReturns() As Variant

ReDim vReturns(1 To Theprices.Rows.Count, 1 To Theprices.Columns.Count)
ReDim vMatrix(1 To Theprices.Rows.Count, 1 To Theprices.Columns.Count)

For vRow = 1 To Theprices.Rows.Count - 1
For vColumn = 1 To Theprices.Columns.Count
vReturns(vRow, vColumn) = (Theprices(vRow, vColumn).Value / Theprices(vRow + 1, vColumn).Value)-1
Next vColumn
Next vRow

vRow = 1
vColumn = 1

For vRow = 1 To Theprices.Columns.Count
For vColumn = 1 To Theprices.Columns.Count
vMatrix(vRow, vColumn) = Application.WorksheetFunction.Covar(vReturns.Columns(vRow), vReturns.Columns(vColumn))
Next vColumn
Next vRow

CovarMatrix = vMatrix



End Function

Kluz
04-23-2008, 08:39 PM
Arrays in VBA do not have a .Columns Property to my knowledge. In the VBA help file titled "Using Arrays" near the bottom it demonstrates how to return a specified value from within an array (in the line that begins: Debug.Print).
I commented out the troublesome line and got a Divide by Zero error in the linevReturns(vRow, vColumn) = (Theprices(vRow, vColumn).Value / Theprices(vRow + 1, vColumn).Value) - 1What is the value of Theprices(vRow + 1, vColumn) when vRow is at the end of the loop and equal to Theprices.Rows.Count?

axupaxu
04-24-2008, 12:09 AM
Arrays in VBA do not have a .Columns Property to my knowledge. In the VBA help file titled "Using Arrays" near the bottom it demonstrates how to return a specified value from within an array (in the line that begins: Debug.Print).
I commented out the troublesome line and got a Divide by Zero error in the linevReturns(vRow, vColumn) = (Theprices(vRow, vColumn).Value / Theprices(vRow + 1, vColumn).Value) - 1What is the value of Theprices(vRow + 1, vColumn) when vRow is at the end of the loop and equal to Theprices.Rows.Count?

A small mistake on my part, the first loop should end at theprices.Rows.Count -1 in order to avoid the divide by zero.

shg
05-04-2008, 09:47 PM
The Index function can reference an entire row or column of a 2D array:
Dim WF As WorksheetFunction
Set WF = WorksheetFunction

' ...

vMatrix(vRow, vColumn) = WF.Covar(WF.Index(vReturns, 0, vRow), WF.Index(vReturns, 0, vColumn))

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum