Sub FilterByYear()
Dim filterYear As Long
Dim ws As Worksheet, summarySheet As Worksheet
Dim lastRow As Long
Dim rng As Range
Dim hiddenRange As Range
Dim cell As Range
Set ws = ThisWorkbook.Worksheets("Sheet1")
Set summarySheet = ThisWorkbook.Worksheets("Summary")
filterYear = ws.Range("M2").Value
lastRow = ws.Cells(ws.Rows.Count, 2).End(xlUp).Row
' Record the range of hidden rows
For Each cell In ws.Rows("4:" & lastRow).Columns(1).Cells
If cell.EntireRow.Hidden Then
If hiddenRange Is Nothing Then
Set hiddenRange = cell.EntireRow
Else
Set hiddenRange = Union(hiddenRange, cell.EntireRow)
End If
End If
Next cell
' Unhide all rows temporarily
ws.Rows("4:" & lastRow).EntireRow.Hidden = False
' Apply filter based on year
ws.Range("A3:K" & lastRow).AutoFilter Field:=2, _
Criteria1:=">=" & DateSerial(filterYear, 1, 1), _
Operator:=xlAnd, _
Criteria2:="<=" & DateSerial(filterYear, 12, 31)
' Check if there are visible rows
On Error Resume Next
Set rng = ws.Range("A4:K" & lastRow).SpecialCells(xlCellTypeVisible)
On Error GoTo 0
If Not rng Is Nothing Then
' Clear existing data on the Summary sheet
summarySheet.Cells.Clear
' Copy filtered cells to the Summary sheet
ws.Rows(3).Copy Destination:=summarySheet.Range("A1") ' Copy header
rng.Copy Destination:=summarySheet.Range("A2") ' Copy filtered data
Else
MsgBox "No data found for the specified year.", vbExclamation
End If
ws.AutoFilterMode = False
' Re-hide rows that were originally hidden
If Not hiddenRange Is Nothing Then
hiddenRange.EntireRow.Hidden = True
End If
End Sub