1

我正在修改此代码,Macro - delete rows based on date

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("Sheet3")

'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:="<8/5/2021"
    .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

到目前为止,我已经添加了一个输入框,用户可以在其中定义他们正在寻找的日期。这很好用。

Sub EditedCode()

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

'turn off alerts
Application.DisplayAlerts = False

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

myValue = InputBox("Enter Date in XX/XX/XXXX Format", "Date Selection", " ")
Range("Y1") = myValue

从这里我想自动过滤输入日期,然后使用 .SpecialCells 删除除所选日期之外的所有内容。我试过使用标准 1/操作员/标准 2,但我无法让它工作。有人知道我在做什么错吗?

当前完整代码:

Sub EditedCode()

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

'turn off alerts
Application.DisplayAlerts = False

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

myValue = InputBox("Enter Date in XX/XX/XXXX Format", "Date Selection", " ")
Range("Y1") = myValue

'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 using above input
'older than inputed date, then deleting
'all the visible rows except the header
With MyRange
    .AutoFilter Field:=1, Criteria1:="=& myValue"
    .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

我还尝试更改 myValue 的类型并在自动过滤器 (<,>,=) 上使用不同的功能。任何帮助表示赞赏。谢谢!

ws 示例

4

0 回答 0