PDA

View Full Version : [SOLVED:] Delete rows with previous dates



jonsonbero
01-25-2023, 05:54 AM
Hello everyone
I need a code that will look at a large data set and check in the date column for any date listed for the previous months and then remove all the rows from the report for the previous months .. Header in O7, data string starts row8 down ... Thanks in advance!!

georgiboy
01-25-2023, 07:14 AM
A few unknowns here as in:
• Do you have filters applied?
• Is it only the previous month or all data before this month to be deleted?
• Is the data within a table object or just data on the worksheet?

Something like the below may work if you have filters already applied:

Sub test()
Dim fDay As Variant, endRow As Long

fDay = DateSerial(Year(Date), Month(Date), 1)
endRow = Range("O" & Rows.Count).End(xlUp).Row

Range("O7").AutoFilter Field:=1, Criteria1:="<" & CLng(fDay)
Range("8:" & endRow).SpecialCells(xlCellTypeVisible).Delete
Range("O7").AutoFilter Field:=1
End Sub

You may be better off sharing an example workbook

jonsonbero
01-25-2023, 08:44 AM
I appreciated your quick response in giving me the above code
I Tested your code but There's a debug during the execution of the code in this line

Range("8:" & endRow).SpecialCells(xlCellTypeVisible).Delete


Note : All data will be deleted before this month and data within a table object
Here's an attachment... Thanks again.

jonsonbero
01-27-2023, 05:57 AM
Your help is much appreciated!

georgiboy
01-27-2023, 07:47 AM
Try it as below instead:

​Sub test()
Dim fDay As Variant, endRow As Long

fDay = DateSerial(Year(Date), Month(Date), 1)
endRow = Range("O" & Rows.Count).End(xlUp).Row

Range("O7").AutoFilter Field:=15, Criteria1:="<" & CLng(fDay)
On Error Resume Next
Range("8:" & endRow).SpecialCells(xlCellTypeVisible).Delete
On Error GoTo 0
Range("O7").AutoFilter Field:=15

End Sub

jonsonbero
01-27-2023, 07:57 AM
Brilliant!! Thank you so much, it's perfect!