代码之家  ›  专栏  ›  技术社区  ›  Anu

为什么SumProduct不能在excelvba中使用

  •  2
  • Anu  · 技术社区  · 6 年前

    脚本

    我想用 COUNTIF COUNTIF公司 Range(poRange) 像这样的 C1:C100 Trim(mainpage.po.value) 像苹果一样

    iVal = Application.WorksheetFunction.CountIf(Range(poRange), Trim(mainPage.po.Value))
    

    iVal = Application.WorksheetFunction.SumProduct(--(EXACT(Range(poRange), Trim(mainPage.po.Value))))
    

    但这次由于编译时错误,我无法运行VBA Sub or Function not defined '

    2 回复  |  直到 6 年前
        1
  •  3
  •   Ambie    6 年前

    问题在于 EXACT WorksheetFunction 不会暴露。

    Evaluate 功能。基本程序如下所示:

    Public Function SumProductExact(rng As Range, testItem As String) As Long
        Dim evalExpr As String
    
        On Error GoTo EH
        evalExpr = "=SUMPRODUCT(--(EXACT(" & rng.Address & ", """ & testItem & """)))"
        SumProductExact = Evaluate(evalExpr)
        Exit Function
    
    EH:
        SumProductExact = -1
    End Function
    

    会被这样称呼:

    Debug.Print SumProductExact(Sheet1.Range("A1:A10"), "Apple")
    

    但对于一个相对琐碎的函数来说,花那么长的时间似乎不值得,所以您可以自己编写 CountIf 函数进行精确匹配。您可能希望将其扩展以适应其他类型的比较,如日期,但从根本上看,它是这样的:

    Public Function CountIfExact(rng As Range, testItem As Variant) As Long
        Dim v As Variant
        Dim c As Long
    
        On Error GoTo EH
        For Each v In rng.Value2
            If v = testItem Then c = c + 1
        Next
    
        CountIfExact = c
        Exit Function
    
    EH:
        CountIfExact = -1
    End Function
    

    其名称如下:

    Debug.Print CountIfExact(Sheet1.Range("A1:A10"), "Apple")
    
        2
  •  0
  •   Anu    6 年前

    Public c As Integer
    
    Sub findVal()
    Call SumProductExact(Sheet1.Range("A1:A10"), "Apple")
    MsgBox c ' You can use this c value for other calculations
    
    End Sub
    
    Public Function SumProductExact(rng As Range, testItem As String) As Long
        Dim evalExpr As String
    
        On Error GoTo EH
        evalExpr = "=SUMPRODUCT(--(EXACT(" & rng.Address & ", """ & testItem & """)))"
        SumProductExact = Evaluate(evalExpr)
        c = SumProductExact
        Exit Function
    
    EH:
        SumProductExact = -1
    End Function
    

    请注意,对于上面的代码,它使用的是静态范围A1:A10和静态名称Apple。您可以根据需要将其更改为动态范围和名称。

    推荐文章