Consulting

Results 1 to 6 of 6

Thread: Delete rows with previous dates

  1. #1

    Delete rows with previous dates

    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!!

  2. #2
    Moderator VBAX Master georgiboy's Avatar
    Joined
    Mar 2008
    Location
    Kent, England
    Posts
    1,192
    Location
    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
    Click here for a guide on how to add code tags
    Click here for a guide on how to mark a thread as solved

    Excel 365, Version 2403, Build 17425.20146

  3. #3
    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.
    Attached Files Attached Files

  4. #4
    Your help is much appreciated!

  5. #5
    Moderator VBAX Master georgiboy's Avatar
    Joined
    Mar 2008
    Location
    Kent, England
    Posts
    1,192
    Location
    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
    Click here for a guide on how to add code tags
    Click here for a guide on how to mark a thread as solved

    Excel 365, Version 2403, Build 17425.20146

  6. #6
    Brilliant!! Thank you so much, it's perfect!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •