Sub testCov()
Rng2 = Sheets("20 Asset Model").Range("b3:f48")
Dim covMatrix() As Variant
ReDim covMatrix(1 To Rng2.Columns.Count, 1 To Rng2.Columns.Count)
Call constructCovMatrix(Rng2, covMatrix)
MsgBox (covMatrix)
End Sub
Sub constructCovMatrix(rng, ByRef covMatrix)
'@rng The Range of the return series.
Dim i As Integer
Dim j As Integer
For i = 1 To rng.Columns.Count
For j = 1 To rng.Columns.Count
covMatrix(i, j) = Application.WorksheetFunction.Covar(rng.Columns(i), rng.Columns(j))
Next
Next
End Sub
The code stops at the line ReDim, saying object missing. Why is this? Thanks
Try this to set your range as a range object be declaring it: (comments in-line)
Note:
You may want to go to the VBA editor’s setting sand click tools > options > Declare varible decleration > checked
This will ensure that you need to declare all your variables.
As is, the above code did not declare
Rng2as a range. So when Excel first sees the nameRng2it creates a Variant type variable and sets it equal to the range of the sheet in the first line. Excel notices thatSheets("20 Asset Model").Range("b3:f48")is an array of cells, and it treats the variantRng2as an array type variable going forward for the rest of your code. Assuming that you want to use the variable namedRng2as a range, we can declare it as such and use theSetcommand to assign it.When you don’t declare your variable types its easy for a mix-up like this to happen.