kajohnson9
New member
I have aworkbook with multiple worksheets. I have various date data in Column C. On the first workshhet, I have a list of years (2022,2023,2024,etc) I want to count the total number of times a particular year (based on the year in a cell in the first sheet) across all worksheets. And I want to call this function from a particular cell in shett 1.
I have tried the following code and I don't see the problem with it. Can someone please help?
Public Function Sum_values_by_year()
'declare a variable
Dim ws As Worksheet
Dim WS_Count As Integer
Dim syear As Integer
WS_Count = ActiveWorkbook.Worksheets.count
syear = ws.Range("F" & ActiveCell.Row) 'This gives me an error 91
sumyears = 0
' Loop through each worksheet
For j = 1 To WS_Count
Worksheets(j).Activate
'sum values by year using the For Loop
For i = 1 To 200
If Year(ws.Cells(i, 3)) = syear Then
sumyears = sumyears + ws.Cells(i, 3).Value
End If
Next i
Next j
ws.Range("G" & ActiveCell.Row) = sumyears
End Function
I have tried the following code and I don't see the problem with it. Can someone please help?
Public Function Sum_values_by_year()
'declare a variable
Dim ws As Worksheet
Dim WS_Count As Integer
Dim syear As Integer
WS_Count = ActiveWorkbook.Worksheets.count
syear = ws.Range("F" & ActiveCell.Row) 'This gives me an error 91
sumyears = 0
' Loop through each worksheet
For j = 1 To WS_Count
Worksheets(j).Activate
'sum values by year using the For Loop
For i = 1 To 200
If Year(ws.Cells(i, 3)) = syear Then
sumyears = sumyears + ws.Cells(i, 3).Value
End If
Next i
Next j
ws.Range("G" & ActiveCell.Row) = sumyears
End Function