Reputation: 33
I'm trying to create a macro that returns the estimated std dev for a portfolio to a cell. However, as the no of shares, their covar as well as their weights will change basically constantly and with the different portfolios i want this in VBA (my ultimate goal is to make my reporting as easy as possible).
I can't seem to understand the ctrl + shift + enter, or the sqr part.
Could you please look at my code help me?
Sub PorteføljeRisiko()
Dim RapportBok As Workbook
Dim RapportArk As Worksheet
Set RapportBok = Workbooks("Rapport kunder")
Set RapportArk = RapportBok.Sheets(1)
Dim Region1 As Long
Dim RegionA As Long
Dim Matrise As Range
(as the no of shares vary, I here find out how many rows that actually include a value(i.e. % weighting in each share))
Region1 = Application.WorksheetFunction.CountIf(RapportArk.Range("AC7:AC18"), "<>" & "")
RegionA = Region1 - 1
(to get the matrix for the covar between shares as the no of shares change with puchase and sale of shares. the matrix starts in cells(3,55)
SisteKolonne = RapportArk.Cells(RegionA + 3, RegionA + 55)
Set Matrise = RapportArk.Range(Cells(3, 55), Cells(3 + RegionA, 55 + RegionA))
Set Region = RapportArk.Range("AC7:AC" & Region1 + 6)
(I want the result in Range("AG21"))
RapportArk.Range("AG21").FormulaArray = MMult(Application.MMult(Region, Matrise), Application.Transpose(Region))
(Everything works fine, except that it returns #VALUE! as i can't seem to get neither the ctrl + shift + enter part nor the SQR part in the macro)
End Sub
Upvotes: 3
Views: 744
Reputation: 29352
First of all what you are computing here in VBA is not a formula
but a value
. Apart of that, I could not verify all your calculations but I could see a problem here:
Application.MMult(Region, Matrise)
The dimensions do not respect the rules of matrix multiplication. From analyzing your code, Region
is a column vector with size Region1
, while Matrise
is a Region1 x Region1
Matrix.
Remember that Matrix multiplication is not commutative. Most likely what you wanted is to switch the order of these operands:
Application.MMult(Matrise, Region)
This will give you a column vector of size Region1
. But then you want to have a dot product with the vector Region
and here again, the row vector should come first, so you should apply the Transpose
on the first operand not on the second one. So the correct statement should be:
RapportArk.Range("AG21").value = _
Application.MMult(Application.Transpose(Application.MMult(Matrise, Region)), Region)
Since the last operation is the dot-product
of two vectors, you can probably simplify it using SumProduct
:
RapportArk.Range("AG21").value = _
Application.SumProduct(Application.MMult(Matrise, Region), Region)
Upvotes: 6