我想编写一个宏,它将删除包含列的日期早于X天的所有行

时间:2017-03-17 05:26:25

标签: excel excel-vba excel-2007 vba

我有一张Excel表格,其中有N行和M列,其中一列有日期值。根据此列中的值,我希望删除日期早于X天的所有行。

我能得到任何帮助吗?提前谢谢!

2 个答案:

答案 0 :(得分:1)

有两种方法可以做到这一点:

  1. 使用公式。只需减去2个日期(下面的示例屏幕截图),然后过滤差异'列根据您的要求删除不需要的数据。 Date Difference using Excel Formula

    。 另一种是使用更加动态的VBA。

    Sub Delete_Rows_based_on_Date()
    
    Dim iRow As Integer, iCol As Integer, iNum As Integer
    Dim iLoopR As Integer, iLoopC As Integer
    'Benchmark Days
    iNum = 7
    
    iRow = Range("A1:A" & Rows.Count).End(xlUp).Row
    iCol = Cells(1, Columns.Count).End(xlToLeft).Column
    
    
    For iLoopR = 1 To iRow   'Assuming data starts from Row #1
        For iLoopC = 1 To iCol   'Assuming data starts from Col #1 (A)
            If IsDate(Cells(iLoopR, iLoopC)) Then ' Check if the cells contains a Date Value
                If DateDiff("d", Now(), Cells(iLoopR, iLoopC)) > iNum Then
                    Cells(iLoopR, iLoopC).EntireRow.Delete
                End If
            End If
        Next iLoopC
    Next iLoopR
    End Sub 
    

答案 1 :(得分:0)

sub deldat()
dim ws as worksheet
dim lrow as variant
dim lcol as variant
dim dt as variant
dim n as variant

n=7 'assuming 7days to delete records

set ws=thisworkbook.sheets(1)
lrow=ws.range("A1:A" & rows.count).end(xlup).row 'Getting Last Row
lcol=ws.Cells(1, .Columns.Count).End(xlToLeft).Column 'Getting Last column
set dt=date() 'getting current date

for i=1 to lrow
cell=ws.cells(i,1) 'Assuming date values in column 1 Or A
if datediff("d",dt,cell.value) > n then
ws.row(i).entirerow.delete
end if
next i
end sub

我不确定代码。我没有测试过。尝试使用此代码并返回此代码中的缺点或错误