COUNTIF in VBA Across Multiple Sheets

kajohnson9

New Member
Joined
Jul 29, 2011
Messages
9
I have a function using COUNTIF where I want to count the number of occurrances of a number (input value) across multiple sheets. I thought this would be straightforward but I can't get it to execute. All I get is a beep when I try. Any help you can give me is appreciated. The code is as follows and it is called from a cell as =countbyyear(F5) where F5 contains a number, like 2024.

VBA Code:
Function CountByYear(myYear)
Dim s$, ws As Worksheet
Dim EachCount As Integer
CountByYear = 0
For Each ws In Worksheets
    If UCase$(ws.Name) <> "TOC" Then
        EachCount = WorksheetFunction.CountIf(Range("C3:C200"), myYear)
        CountByYear = CountByYear + EachCount
    End If
Next
End Function
 
Last edited by a moderator:
The range needs to be referenced to each worksheet or else each time it will use that range on the active sheet. Try this instead

VBA Code:
Function CountByYear(myYear) As Long
  Dim ws As Worksheet
  Dim EachCount As Long
 
  For Each ws In Worksheets
      If UCase$(ws.Name) <> "TOC" Then
          EachCount = WorksheetFunction.CountIf(ws.Range("C3:C200"), myYear)
          CountByYear = CountByYear + EachCount
      End If
  Next
End Function

When posting vba code in the forum, please use the available code tags. It makes your code much easier to read/debug & copy. My signature block at the bottom of this post has more details. I have added the tags for you this time. 😊

I also suggest that you update your forum profile (click your user name at the top right of the forum, then ‘Account details’) so helpers always know what Excel version(s) & platform(s) you are using as the best solution often varies by version. (Don’t forget to scroll down & ‘Save’)
 
Upvote 0

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top