excel - 宏中的 Sumproduct
问题描述
我正在尝试使用该SUMPRODUCT
函数与SUMIF
. 但是当我运行宏时,我得到了……</p>
运行时错误 13.
我试图在一个看起来像这样的单元格中制作相同的功能。
=SUMPRODUCT(SUMIF(B2:B3,K15:K18,L15:L18))
它工作正常,所以我知道这个概念已经得到证明。
Sub GrandTotal() 'Finds the last non-blank cell in a single row or column
Dim lRow As Long
Dim lCol As Long
Dim GrandTotal As Variant
Dim MyRg1 As Variant
Dim MyRg2 As Variant
Dim MyRg3 As Variant
'Find the last non-blank cell in column A(1)
lRow = Cells(Rows.Count, 1).End(xlUp).Row
'Find the last non-blank cell in row 1
lCol = Cells(1, Columns.Count).End(xlToLeft).Column
MsgBox "Last Row: " & lRow & vbNewLine & _
"Last Column: " & lCol
'set range
Set MyRg1 = Range("B2:B3")
'set criteria
Set MyRg2 = Range("$K$15:$K$18")
'set sum range
Set MyRg3 = Range("$L$15:$L$18")
For Each cell In Range(Cells(lRow, 2), Cells(lRow, lCol))
GrandTotal = WorksheetFunction.SumProduct(WorksheetFunction.SumIf(MyRg1, MyRg2, MyRg3))
cell.Value = GrandTotal
Next cell
End Sub
我找到了一些如何在 VBA 中使用该函数的指南,并且我遵循了相同的原则,我还在堆栈上看到了另一篇文章,显示了如何做,但我得到了错误。
希望某个善良的灵魂可以提供帮助
解决方案
首先,分配给 Range 对象的每个变量都可以声明为 Range,而不是 Variant。此外,传递给 SUMIF 的范围似乎不正确。第一个参数或条件范围应与第三个参数或总和范围的大小相同。所以我将假设分配给 MyRg1 和 MyRg2 的范围应该是相反的。所以首先我们应该有以下...
Dim MyRg1 As Range
Dim MyRg2 As Range
Dim MyRg3 As Range
'set criteria range
Set MyRg1 = Range("$K$15:$K$18")
'set criteria
Set MyRg2 = Range("B2:B3")
'set sum range
Set MyRg3 = Range("$L$15:$L$18")
其次,您将无法以这种方式使用 WorksheetFunction.Sumproduct。但是,您可以使用 Evaluate 方法。
GrandTotal = Evaluate("SUMPRODUCT(SUMIF(" & MyRg1.Address & "," & MyRg2.Address & "," & MyRg3.Address & "))")
但请注意,Evaluate 方法有一个限制。它不接受超过 255 个字符。无论如何,既然要将结果转移到一个单元格中,你可以先在单元格中输入实际的公式,然后将其转换为一个值......
With cell
'enter the formula in the current cell
.Formula = "=SUMPRODUCT(SUMIF(" & MyRg1.Address & "," & MyRg2.Address & "," & MyRg3.Address & "))"
'convert the formula into a value
.Value = .Value
End With
希望这可以帮助!
推荐阅读
- firebase - 如何检测与 google 和 firebase 的首次身份验证?
- angular - debounceTime rxjs 运算符和输入 keyup 函数的 http 请求问题
- r - 从另一个数据框 r 中添加/减去数据框行
- android - 使用相同布局中的过渡动画布局更改
- python - 我的脚本没有提取所有广告详细信息,而且我没有得到正确的数字
- javascript - 使用“chrome.webNavigation.onCompleted.addListener”时获取“”Uncaught TypeError:无法添加侦听器“
- android - Recyclerview 不显示警报对话框中的数据列表
- ajax - 块上传不适用于大文件 - Laravel 5.8
- aws-lambda - 如何从 Postman 调用受授权人保护的 Lambda?
- powershell - 如何使用 PSM1 文件安装模块?