Hi Guys, as the title said, I am having difficulty on fixing run-time error on this code that I have found. Basically this aims to delete all dates more than 1 months of today's month. Example Today is February, everything on and after April 1 will be deleted. Thanks a lot in advance!
VBA Code:
Sub DeleteRowsLaterThanTwoMonths()
Dim lCol As Long
Dim lLastRow As Long
Dim lRow As Long
Dim dToday As Date
Dim dCellDate As Date
Dim dTwoMonthsLater As Date
'Determine the column number of the "Next Progression Date" column
lCol = FindColumn("Next Progression Date")
'Get today's date
dToday = Date
'Determine two months later
dTwoMonthsLater = DateSerial(Year(dToday), Month(dToday) + 2, 1)
'Determine the last row in the "Next Progression Date" column
lLastRow = ActiveSheet.Cells(Rows.Count, lCol).End(xlUp).Row
'Start at the bottom of the "Next Progression Date" column and work up
For lRow = lLastRow To 1 Step -1
'Get the date value in the current cell
dCellDate = Cells(lRow, lCol).Value
'Check if the date value is later than two months from today
If dCellDate >= dTwoMonthsLater Then
'Delete the entire row that contains the cell
Rows(lRow).Delete
End If
Next lRow
End Sub
'Function to find the column number of a header
Function FindColumn(sHeader As String) As Long
FindColumn = Cells.Find(What:=sHeader, LookAt:=xlWhole, SearchOrder:=xlByColumns, _
SearchDirection:=xlNext, MatchCase:=False).Column
End Function