Sub FilterByYear()
Dim filterYear As Long
Dim ws As Worksheet, newSheet As Worksheet
Dim lastRow As Long
Dim rng As Range
Set ws = ThisWorkbook.Worksheets("Sheet1")
filterYear = ws.Range("M2").Value
lastRow = ws.Cells(ws.Rows.Count, 2).End(xlUp).Row
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
' Create a new sheet
Set newSheet = ThisWorkbook.Sheets.Add
newSheet.Name = "FilteredData_" & filterYear
' Copy filtered cells to the new sheet
ws.Rows(3).Copy Destination:=newSheet.Range("A1") ' Copy header
rng.Copy Destination:=newSheet.Range("A2") ' Copy filtered data
Else
MsgBox "No data found for the specified year.", vbExclamation
End If
ws.AutoFilterMode = False
End Sub