【问题标题】:Excel Macro - Delete Row based upon variable date rangeExcel 宏 - 根据可变日期范围删除行
【发布时间】:2016-10-28 12:27:23
【问题描述】:

我需要删除给定日期范围之外的所有行。我能够记录一个宏,但这仅适用于给定的数据集,并且随着添加更多数据而无法删除所有适当的行。我未能成功修改在主题中找到的其他宏,这些宏询问完全相同的事情......对不起。

日期交易日期在 C 列中,最早的在单元格 J1 中(通常是一个公式,如果这很重要,但我可以更改它),日期范围的结束在单元格 L1 中。

我尝试使用 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``

提前谢谢你!

【问题讨论】:

  • 您要删除column C 的任何单元格中日期小于 01/01/2013 的任何行吗?我对你提到J1L1 感到困惑
  • 单元格 J1 将具有我想要保留的最早日期,L1 将具有我想要保留的最后日期。这两个单元格仅提供宏需要保留的日期范围。 2013 年 1 月 1 日是我尝试修改数据的宏之一的一部分。我尝试添加图片,但我的积分还不够。

标签: excel macros vba


【解决方案1】:
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

我认为这会奏效

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-22
    • 2020-11-15
    • 1970-01-01
    相关资源
    最近更新 更多