2

我试图用多个标准得到总和:

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

从下图中可以看出,我设法在 Excel 中使用 SumProduct 得到答案。当我尝试使用 VBA 获得与 SumProduct 相同的答案时,我收到错误 13 类型不匹配。

图片:

在此处输入图像描述

有什么建议吗?

代码:

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
4

1 回答 1

5

三件事

  1. rng1, rng2, rng3, Criteria1 and Criteria2是变量。当你把它们放在双引号内时,它们就变成了一个字符串。
  2. 您已声明resultDouble. 将其声明为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 & _
                                   ")")
于 2019-02-26T08:57:20.590 回答