Excel 将sum积函数转换为VBA

Excel 将sum积函数转换为VBA,excel,vba,countif,Excel,Vba,Countif,我正在尝试编写包含以下行的代码: WorksheetFunction.SumProduct((Columns(3) = ActiveCell.Value) + 0) 代码总是返回类型不匹配错误 我使用这行代码是为了避免使用长度超过255个字符串的Countif函数 提前谢谢 这是原始代码: Dim MyColumn As Long, r As Long, lngLastRow As Long MyColumn = ActiveCell.Column With Sheets("Project B

我正在尝试编写包含以下行的代码:

WorksheetFunction.SumProduct((Columns(3) = ActiveCell.Value) + 0)
代码总是返回类型不匹配错误

我使用这行代码是为了避免使用长度超过255个字符串的Countif函数

提前谢谢

这是原始代码:

Dim MyColumn As Long, r As Long, lngLastRow As Long
MyColumn = ActiveCell.Column
With Sheets("Project Breakdown")
lngLastRow = .Cells(.Rows.Count, MyColumn).End(xlUp).Row
    For r = lngLastRow To 1 Step -1
        If InStr(1, Cells(r, MyColumn - 2), "DIV", vbTextCompare) = 0 And InStr(1, Cells(r, MyColumn - 2), "SEC", vbTextCompare) = 0 Then
             If WorksheetFunction.CountIf(.Columns(MyColumn), .Cells(r, MyColumn).Value) > 1 Then
            .Cells(r, MyColumn).Delete Shift:=xlUp
             End If
        End If
    Next r
End With

countif返回一个错误,因为字符串长度超过255,所以我尝试改用sumproduct函数,但无法使其工作。

问题是您将一个范围与单个值进行比较。 这适用于excel公式,但不适用于vba

一种解决方法是在工作表中使用一个额外的列,例如

=if($C1='some value',1,0)
然后取这列的和

或者,您也可以在excel中计算产品。在预定义单元格(例如A1)中写入活动单元格的值,并让您的SUM产品使用以下公式:

=sumproduct((C:C=$A$1)+0)
更新: 假设A1为自由单元,A2包含以下公式:

=SumProduct((C:C=$A$1)+0)
通过将A1的值更改为当前单元格,此公式包含结果

Dim MyColumn As Long, r As Long, lngLastRow As Long
MyColumn = ActiveCell.Column
With Sheets("Project Breakdown")
lngLastRow = .Cells(.Rows.Count, MyColumn).End(xlUp).Row
    For r = lngLastRow To 1 Step -1
        If InStr(1, Cells(r, MyColumn - 2), "DIV", vbTextCompare) = 0 And InStr(1, Cells(r, MyColumn - 2), "SEC", vbTextCompare) = 0 Then
             .cells(1,1).value = .cells(r, MyColumn).value
             ' Might be necessary to call .Calculate here to assure that A2 contains its new value
             If .cells(1,2) > 1 Then
            .Cells(r, MyColumn).Delete Shift:=xlUp
             End If
        End If
    Next r
End With

您是否检查了其他计数函数(如COUNTA)?您想用什么对C列中的值进行多重化?什么列或范围?请查看更新。谢谢你能解释一下你想用你的代码实现什么吗?也许你们两个都不需要functions@ShaiRado好啊我试图编写一个代码来删除C列中的重复项,但基于a列的条件是,只要a列不包含单词“DIV”或“SEC”,代码就会删除C列中的重复项。它工作得很好,但当字符串长度超过255时,会出现错误:(非常抱歉,但我仍然无法理解您所说的信息将如何帮助我获得所需的行代码。请查看原始帖子中的更新,因为我无法修复activecell。它会在for next循环中进行更改!它确实有效,但需要大量时间才能完成:(…是否有其他方法或正确的语法可以让SumProduct正确执行如果您只需要知道是否有发生,您可以使用Range.find方法。如果没有。columns(3)。find(ActiveCell.value)什么都不是。。。