VBA countif语句只返回0
我正在研究一个应该计算“GM”这个词出现在列中的次数的macros。 我决定使用countif语句,就像我以前那样,它运行良好。 但是,由于某种原因,当我运行我的代码时,它每次输出0,这肯定是不正确的。 我已经运行这个相同的代码与其他列和string,它工作正常,但由于某种原因,如果我search这个特定列的术语“通用汽车”失败。 我能想到的唯一可能是countif只有在你search的string是单元格中唯一的string时才起作用,因为在所有情况下,代码都可以正常工作。 在这种特殊情况下,我正在查找的string不是单元格中的唯一string,代码失败。 我试图find更多的信息是否这是真实的,但我无法find任何东西在线。 这里是代码,如果有人想看看:
Function OemRequest() As Long Sheets("CS-CRM Raw Data").Select Sheets("CS-CRM Raw Data").Unprotect Dim oem As Long Dim LastRow As Long Dim LastColumn As Long 'Determines size of table in document LastRow = Range("A" & Rows.Count).End(xlUp).row LastColumn = Cells(1, Columns.Count).End(xlToLeft).Column oem = Application.WorksheetFunction.CountIf(Range(2 & "2:" & 2 & LastRow), "gm") OemRequest = oem End Function
您所写的COUNTIF
只能匹配整个内容为“gm”的单元格。 COUNTIF
函数中的条件也会接受通配符,所以要匹配包含“gm”的单元格do:
.CountIf(Range(2 & "2:" & 2 & LastRow), "*gm*")
更新
正如你所指出的,你的Range
调用也有一个问题。 实际上,parens中的expression式将评估为"22:2<LastRow>"
(其中<LastRow>
是LastRow
variables的值)。
那里的2
应该是一个包含你感兴趣的列名的variables。
Dim col as String col = "B" ... Range(col & "2:" & col & LastRow) ...
这将评估为"B2:B<LastRow>"
,这是你想要的。
另一种可能性
oem = WorksheetFunction.CountIf(Columns(LastColumn).Cells(2).Resize(rowsize:=LastRow - 1), "gm")
这将统计表格的最后一列中包含"gm"
单元格(如果需要,请使用wilcards),除了第一行中的单元格。 (假设表格左上angular在单元格"A1"
)
当然,如果您想要计算其他列,您可以创build一个variables:
Dim lngCol as Long lngCol = ... oem = WorksheetFunction.CountIf(Columns(lngCol).Cells(2).Resize(rowsize:=LastRow - 1), "gm")
我以这种方式思考
Sub Main() Application.ScreenUpdating = 0 Dim Count As Double Range("C1").Activate 'Firs row in the column Do While ActiveCell.Value <> "" If InStr(ActiveCell.Value, "MyText") Then Count = Count + 1 End If ActiveCell.Offset(1, 0).Activate Loop Application.ScreenUpdating = 1 End Sub
这将工作,只有当数据单元不是空的,如果在工作表中间有一个空的空间,做到这一点:
Sub Main() Application.ScreenUpdating = 0 Dim Count As Double Range("C1").Activate Do While ActiveCell.Row <> Rows.Count ' This wil evaluate all the rows in the 'C' Column If InStr(ActiveCell.Value, "MyText") Then Count = Count + 1 End If ActiveCell.Offset(1, 0).Activate Loop Application.ScreenUpdating = 1 End Sub
希望这是为你工作。