0

我正在尝试使用该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 中使用该函数的指南,并且我遵循了相同的原则,我还在堆栈上看到了另一篇文章,显示了如何做,但我得到了错误。

希望某个善良的灵魂可以提供帮助

4

4 回答 4

2

首先,分配给 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

希望这可以帮助!

于 2019-06-23T15:22:24.627 回答
0

错误 13 是类型不匹配错误。我查阅了WorksheetFunction.SumIf的文档。它说第一个参数应该是 Range 类型,第二个和第三个参数应该是 Variant。我现在无法测试,但尝试将 MyRg1 声明为 Range。

于 2019-06-23T13:02:17.220 回答
0

这将是ConvertFormula的一个很好的用途,因为您已经在 Excel 中成功构建了公式,您只需要 VBA 来生成值。请注意,convertformula 无法处理超过 255 个字符的公式。

以下是您应用它的大致方法。它是

Sub heresExample()

'formula with the cell in exitance
Dim fCell As Range
Set fCell = Range("G10") 'set this up with a formula that works for 
   'if you were to copy paste formula.



'Your original code modified
Dim cell As Range
For Each cell In Range(Cells(lRow, 2), Cells(lRow, lCol)).Cells

        'Takes the formula and applies the value if from that exact cell.
        '(you don't really need grand total)
        GrandTotal = Evaluate(Application.ConvertFormula(fCell.Formula2R1C1, xlR1C1, xlA1, , cell))

        cell.Value = GrandTotal
Next cell


End Sub
于 2019-06-24T08:22:13.343 回答
0

功能正常工作后,您可以打开宏记录器,单击具有所需功能的单元格,按 F2,然后按 Enter。您将拥有可以满足您需求的 VBA。

于 2019-06-25T11:37:54.990 回答