如何获得WorksheetFunction.SumProduct()值匹配= SUMPRODUCT()?

时间:2015-02-23 07:03:09

标签: excel vba excel-vba

我尝试使用SUMPRODUCT来确定某个范围内的所有非空值是否相同。我能够使用this answer将其作为Excel公式使用,现在我希望使用WorksheetFunction.SumProduct()在VBA中获得结果。

我尝试了以下内容:

Public Function onlyOneValue(sheet As Worksheet) As Boolean

Dim sumProduct As Variant
Dim rng As Range
Dim rngAddress As String
Dim sumProductString As String
Dim column As Long

    Set rng = sheet.Range(sheet.Cells(5,20), _
                        sheet.Cells(65,20))
    rngAddress = rng.address
    sumProductString = "(" & rngAddress & "<>"""")/countif(" & _
                                            rngAddress & "," & rngAddress & "&"""")"
    sumProduct = WorksheetFunction.sumProduct(Evaluate(sumProductString))
    onlyOneValue = sumProduct = 1
End If

End Function

当我使用所有非空白值相同的列进行测试时,sumProduct的值为1.63934426229508E-02,但是当我将sumProductString复制到=SUMPRODUCT()时在工作表上的公式,我得到1的预期值。

如果我不使用Evaluate()而是使用:

WorksheetFunction.sumProduct(sumProductString)

然后我收到了这个错误:

Unable to get the SumProduct property of the WorksheetFunction class

如何在VBA中实现此功能?

1 个答案:

答案 0 :(得分:2)

当我将SUMPRODUCT添加到Evaluate并调整即:

)时,它对我有用
Public Function onlyOneValue(sheet As Worksheet) As Boolean

Dim rng As Range
Dim rngAddress As String
Dim sumProductString As String

    Set rng = sheet.Range(sheet.Cells(5, 20), _
                        sheet.Cells(65, 20))
    rngAddress = rng.Address
    sumProductString = "=SUMPRODUCT((" & rngAddress & "<>"""")/countif(" & _
                                            rngAddress & "," & rngAddress & "&""""))"

    onlyOneValue = (CLng(Evaluate(sumProductString)) = 1)

End Function