I want to use following SUMPRODUCT
formula in VBA:
=SUMPRODUCT((Sale!$J$5:$J$1048576=C12)*Sale!$D$5:$D$1048576,Sale!$M$5:$M$1048576)
I used this code but it gives an error
Run-time error '13': Type mismatch
Dim slWks As Worksheet
Set slWks = Sheets("Sale")
ActiveSheet.Range("F12").Value = _
Application.WorksheetFunction.SumProduct((slWks.Range("J5:J1048576") = _
ActiveSheet.Range("C12")) * slWks.Range("D5:D1048576"), slWks.Range("M5:M1048576"))
How can I write that formula with its values using vba?
Taking a guess at your use case:
C12
is some product you are interested inSale!$J$5:$J$1048576
is a range of products(Sale!$J$5:$J$1048576=C12)
gives an array like{1,1,1,0,0,0...}
Sale!$D$5:$D$1048576
is a range of unit pricesSale!$M$5:$M$1048576
is a range of number of units soldSUMPRODUCT
gives a the revenue of for the product inC12
So for this sample data:
You could use this code to do leverage
SUMPRODUCT
:I had the same problem with sumproduct function and after many experiments I solved my problem with this code:
Two possible simple solutions, given that worksheetfunction methods won't work with arrays the size that you are using:
First, add the formula and then replace it with its value
Second, use
Evaluate
: