我想在VBA中使用以下SUMPRODUCT
公式:
=SUMPRODUCT((Sale!$J$5:$J$1048576=C12)*Sale!$D$5:$D$1048576,Sale!$M$5:$M$1048576)
我使用了这段代码但却出错了
运行时错误' 13':类型不匹配
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"))
如何使用vba编写该公式及其值?
答案 0 :(得分:4)
两种可能的简单解决方案,因为工作表函数方法不适用于您正在使用的数组:
首先,添加公式,然后将其替换为值
With activesheet.Range("F12")
.Formula =" =SUMPRODUCT((Sale!$J$5:$J$1048576=C12)*Sale!$D$5:$D$1048576,Sale!$M$5:$M$1048576)"
.Value2 = .Value2
End With
其次,使用Evaluate
:
With Activesheet
.range("F12").Value2 = .Evaluate("SUMPRODUCT((Sale!$J$5:$J$1048576=C12)*Sale!$D$5:$D$1048576,Sale!$M$5:$M$1048576)")
End With
答案 1 :(得分:2)
猜测你的用例:
C12
是您感兴趣的产品Sale!$J$5:$J$1048576
是一系列产品(Sale!$J$5:$J$1048576=C12)
提供了一个类似{1,1,1,0,0,0...}
Sale!$D$5:$D$1048576
是一系列单价Sale!$M$5:$M$1048576
是一系列销售单位数SUMPRODUCT
给出了C12
对于此示例数据:
您可以使用此代码来利用SUMPRODUCT
:
Option Explicit
Sub SumProductWithVBA()
Dim ws As Worksheet
Dim strProduct As String
Dim dblRevenue As Double
Dim wsf As WorksheetFunction
Dim v1 As Variant, v2 As Variant, v3 As Variant, v4 As Variant
Dim i As Long
Set wsf = Application.WorksheetFunction
Set ws = ThisWorkbook.Worksheets("Sheet1")
' condition for SUMPRODUCT
strProduct = ws.Range("A1").Value
' get the values of the ranges
v1 = wsf.Transpose(ws.Range("A4:A15").Value)
v2 = wsf.Transpose(ws.Range("B4:B15").Value)
v3 = wsf.Transpose(ws.Range("C4:C15").Value)
' make the array like {1,1,1,0,0,0...etc}
' this is the equivalent of the SUMPRODUCT((range=value)... bit
ReDim v4(1 To UBound(v1))
For i = 1 To UBound(v1)
If v1(i) = strProduct Then
v4(i) = 1
Else
v4(i) = 0
End If
Next i
' now do the SUMPRODUCT with all the arrays set-up
dblRevenue = wsf.SumProduct(v4, v2, v3)
' test the output
MsgBox dblRevenue
End Sub
答案 2 :(得分:1)
我遇到了与sumproduct函数相同的问题,经过多次实验,我用这段代码解决了我的问题:
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
// show spinner if data is not available yet
self.myModel?.observable?
.subscribe(onNext : { (additionalData) in
self.updateMyTab(additionalData)
// hide spinner
})
.disposed(by: self.disposeBag)
}