我尝试使用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中实现此功能?
答案 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