Option Explicit
'Developed in Excel 2003
'Coded to be in an add-in that modifies the activeworkbook
'File assumed to be set up with some worksheets having tables of data
'
'Worksheets with cell "A1" value "Date" assumed to have row 1 header: date on these worksheets
'will be sorted on date and then records with data values more than some age will be deleted
Sub test()
Const lng_MAXIMUM_YEARS_AGE_TO_KEEP_RECORDS As Long = 3
Dim strFilter As String
Dim wks As Worksheet, wbk As Workbook
If ActiveWorkbook Is Nothing Then Exit Sub 'abort if there is no active workbook
Set wbk = ActiveWorkbook
'confirm that the code is to run on the activeworkbook
If MsgBox(Prompt:=wbk.Name, Buttons:=vbYesNo, Title:="Try to delete records from file ...") = vbNo Then Exit Sub
Application.ScreenUpdating = False
Application.EnableEvents = False
strFilter = "<" & CLng(DateAdd("yyyy", -lng_MAXIMUM_YEARS_AGE_TO_KEEP_RECORDS, Date))
For Each wks In wbk.Worksheets
If IsDataWorksheet(TestWks:=wks) Then Call DeleteOldRecords(FromWks:=wks, FilterColumn:=1, FilterText:=strFilter)
Next wks
Set wks = Nothing
Set wbk = Nothing
Application.EnableEvents = True
MsgBox "Done"
End Sub
'data worksheets are identifiable by cell "A1" being value "Date"
Function IsDataWorksheet(ByRef TestWks As Worksheet) As Boolean
IsDataWorksheet = False
If TestWks.Range("A1").Value = "Date" Then IsDataWorksheet = True
End Function
Sub DeleteOldRecords(ByRef FromWks As Worksheet, ByVal FilterColumn As Long, ByVal FilterText As String)
If FromWks.AutoFilterMode Then FromWks.Range("A1").AutoFilter 'remove any existing autofilter/s
With FromWks.Range("A1").CurrentRegion
.Sort Key1:=.Range("A1"), Order1:=xlAscending, Header:=xlYes 'for speed, sort data before deletions
'remove unwanted records
.AutoFilter Field:=FilterColumn, Criteria1:=FilterText, Operator:=xlAnd
.Offset(1).SpecialCells(xlCellTypeVisible).EntireRow.Delete
.AutoFilter
End With
End Sub