将SumProduct函数转移到VBA中

我试图写一个代码包含以下行:

WorksheetFunction.SumProduct((Columns(3) = ActiveCell.Value) + 0) 

代码总是返回types不匹配错误!

我正在使用该行代码来避免使用长度超过255string的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返回一个错误,因为string长度超过了255,所以我尝试使用sumproduct函数,而不能使其工作。

问题是你将Range与单个值进行比较。 这在excel公式中有效,但不在vba中。

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

 =if($C1='some value',1,0) 

然后拿这个栏的总和。

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

 =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