SumProduct公式错误13类型不匹配

时间:2019-02-26 08:32:04

标签: excel vba sumproduct

我试图通过多个条件求和:

  • “获取”(A列)
  • “是”(C列)
  • K列总和

从下图可以看出,我设法在excel中使用SumProduct得到了答案。当我尝试使用VBA使用SumProduct获得相同的答案时,我收到一条错误消息13 Type Mismatch。

图片:

https://docs.microsoft.com/en-us/javascript/api/office/office.dialogoptions?view=office-js#promptbeforeopen

有什么建议吗?

代码:

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 个答案:

答案 0 :(得分:5)

三件事

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

这是您要尝试的吗? (未测试

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