简体   繁体   中英

Excel Macro - Delete Row based upon variable date range

I need to delete all rows that are outside of a given date range. I was able to record a macro, but that only worked for a given data set, and would fail to delete all of the appropriate rows as more data was added. I have been unsuccessful in modifying other macros that I have found in topics asking about the exact same thing....sorry.

The date transaction dates are in column C, the earliest is in cell J1 (is often a formula, if that matters, but I could change that), and end of the date range is in cell L1.

I tried to use this code previously posted by Dan Wagner:

    Option Explicit
Sub DeleteDateWithAutoFilter()

Dim MySheet As Worksheet, MyRange As Range
Dim LastRow As Long, LastCol As Long

'turn off alerts
Application.DisplayAlerts = False

'set references up-front
Set MySheet = ThisWorkbook.Worksheets("Sheet1")

'identify the last row in column A and the last col in row 1
'then assign a range to contain the full data "block"
With MySheet
    LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
    LastCol = .Range("A" & .Columns.Count).End(xlToLeft).Column
    Set MyRange = .Range(.Cells(1, 1), .Cells(LastRow, LastCol))
End With

'apply autofilter to the range showing only dates
'older than january 1st, 2013, then deleting
'all the visible rows except the header
With MyRange
    .AutoFilter Field:=1, Criteria1:="<1/1/2013"
    .SpecialCells(xlCellTypeVisible).Offset(1, 0).Resize(.Rows.Count).Rows.Delete
End With

'turn off autofilter safely
With MySheet
    .AutoFilterMode = False
    If .FilterMode = True Then
        .ShowAllData
    End If
End With

'turn alerts back on
Application.DisplayAlerts = True

End Sub``

Thank you in advance!

dim row as long
dim lastrow as long
dim mindate as date
dim maxdate as date

mindate = cdate(Cells(1,10))
maxdate = cdate(Cells(1,12))

lastrow = Cells(Rows.Count,"C").End(xlUp).Row
row = 1 'Set here the starting row for checking transaction dates
do while row <= lastrow
transdate = cdate(cells(row,3))
    if transdate < mindate or transdate > maxdate then
        rows(row).entirerow.Delete
    else
        row = row + 1
    end if
loop

I think this will work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM