计算包含特定行的特定值(" N")的单元格数量("嘿")

时间:2015-03-14 06:05:57

标签: excel excel-vba vba

我试图在包含特定单词的特定行中计算包含特定值(" 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

1 个答案:

答案 0 :(得分:0)

它对我有用,但我注意到了

  • 您正在寻找使用xlWhole完全匹配的内容。如果您希望匹配" A嘿,这个单元格位于某个地方"
  • ,请使用xlPart
  • 您的代码具有不必要的选择,并且逐个单元格而不是范围
  • 应用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