vba 在多张纸上计算

vba countif on multiple sheets

请在中间找到下面的代码和注释

Sub Test()

Dim wSheet As Worksheet
Dim myempid As Variant

For Each wSheet In Worksheets

    Select Case (wSheet.Name)

        Case "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"

        empid2 = Worksheets("DB").Range("C13").Value2

        With Worksheets(wSheet.Name)

           'locate the row for the value
            myempid = Application.Match(empid2, .Columns("D"), 0)

            If IsError(myvalueRow) Then
                Debug.Print "empid not found in column D"
                Exit Sub
            End If

            If myempid >= 0 Then
                MsgBox ("Hi")

            '***

'(instead of the message box , i need to count the value "PL" from ("F5:AJ500") for example if myempid is in a _ col range("D8") of sheet jan , we need to count from (F8:AJ8). like wise all the values of myempid should be count in each and every sheets._ 'the sum total of count (PL) in all sheets matching the myempid should be displayed in a msgbox.


            End If
      End With

      Case Else

    End Select

Next wSheet

End Sub

您可以使用Range.Column到return范围对象中单元格的列号。您也可以使用 Application.WorksheetFunction.CountIf 来计算范围内包含特定值的单元格。

我不是 100% 清楚你想做什么,但根据你的例子,如果你有一个特定的单元格引用(例如,在像下面的 MyCell 这样的对象中),你可以调整这个:

Sub myCountIf()
    Dim myCell As Range
    Set myCell = Range("D8")
    MsgBox Application.WorksheetFunction.CountIf(Sheets("DB").Range("F" & myCell.Column & ":AJ" & myCell.Column), "PL")
End Sub

这里有关于 WorksheetFunction.CountIf Method 的更多信息。