SumProduct 公式错误 13 类型不匹配

SumProduct formula Error 13 Type mismatch

我正在尝试使用多个条件求和:

正如您从下图中看到的那样,我设法在 excel 中使用 SumProduct 得到了答案。当我尝试使用 VBA 与 SumProduct 获得相同的答案时,我收到错误 13 Type Mismatch.

图片:

有什么建议吗?

代码:

Option Explicit

Sub test()

    Dim Criteria1 As String, Criteria2 As String
    Dim Lastrow As Long, Result As Double
    Dim rng1 As Range, rng2 As Range, rng3 As Range

    With ThisWorkbook.Worksheets("Sheet1")

        Lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row

        Set rng1 = .Range("A3:A" & Lastrow)
        Set rng2 = .Range("C3:C" & Lastrow)
        Set rng3 = .Range("K3:K" & Lastrow)

        Criteria1 = "Get"
        Criteria2 = "Yes"

        Result = Application.Evaluate("SumProduct(--(rng1 = Criteria1),--(rng2 = Criteria2),--rng3))")

    End With

End Sub

三件事

  1. rng1, rng2, rng3, Criteria1 and Criteria2 是变量。当你把它们放在双引号内时,它们就变成了一个字符串。
  2. 您已将 result 声明为 Double。将其声明为 Variant。这导致了不匹配错误。
  3. 您实际尝试的公式是 =SUMPRODUCT(--($A:$A = "Get"),--($C:$C = "Yes"),--$K:$K)。条件应该用双引号引起来。

这是你正在尝试的吗? (未测试)

    Result = Application.Evaluate("SumProduct(--(" & _
                                   rng1.Address & _
                                   " = """ & _
                                   Criteria1 & _
                                   """),--(" & _
                                   rng2.Address & _
                                   " = """ & _
                                   Criteria2 & _
                                   """),--" & _
                                   rng3.Address & _
                                   ")")