在包含特定单词(“嗨”)的特定行中计算包含特定值(“N”)的单元格数量

我正在计算包​​含特定字(“嘿”)的特定行中包含特定值(“N”)的单元格的数量。

它对第一张纸很好,但对下一张纸不起作用。 注意:“嘿”总是在第二列,但位置不固定

以下是我所尝试的:

Private Sub macro1() Dim SearchString As String Dim far As Range Dim sh As Worksheet Dim c As Integer, count As Integer, i As Integer c = 0 count = 0 SearchString = "Hey" Application.FindFormat.Clear For Each sh In ActiveWorkbook.Worksheets sh.Select Range("B1:B100").Select Set far = Cells.Find(What:=SearchString, _ After:=sh.Cells(1, 1), _ LookIn:=xlValues, _ LookAt:=xlWhole, _ SearchOrder:=xlByRows, _ SearchDirection:=xlNext, _ MatchCase:=True, _ SearchFormat:=False) If Not far Is Nothing Then Application.Goto far For i = 3 To 23 c = Application.WorksheetFunction.CountIf(Cells(ActiveCell.Row, i), "N") If c Then count = count + 1 End If Next i End If Next MsgBox ("Count= " & count) End Sub 

它确实为我工作,但我注意到这一点

  • 你正在寻找使用xlWhole完全匹配。 如果你正在寻找匹配“ 嘿,在这个单元格的某个地方 ”,请使用xlPart
  • 你的代码有不必要的select,而COUNTIF是逐个单元而不是一个范围

更新的代码

 Private Sub macro1() Dim SearchString As String Dim far As Range Dim sh As Worksheet Dim c As Integer, count As Integer SearchString = "Hey" For Each sh In ActiveWorkbook.Sheets Set far = sh.Range("B1:B100").Find(SearchString, , xlValues, xlWhole, xlByRows, xlNext, True, False) If Not far Is Nothing Then c = Application.WorksheetFunction.CountIf(far.Resize(1, 22), "N") count = count + c End If Next MsgBox ("Count= " & count) End Sub