我正在尝试删除列A值(格式化为日期)小于今天日期的所有行。我必须在整个非空A列中运行它们。但面临一个问题,代码以循环遍及整行运行。每次删除只有1行。请让我知道如何在整个行集中运行它。
Sub DeleteRowBasedOnDateRange()
Dim spem As Workbook
Dim ws As Worksheet
Dim N As Long, I As Long
Set spem = Excel.Workbooks("SwitchP.xlsm")
Set ws = spem.Worksheets("data")
N = ws.Cells(Rows.count, "A").End(xlUp).row
For I = 2 To N
If Cells(I, "A").Value < Date Then
Cells(I, "A").EntireRow.Delete
I = I + 1
End If
Next I
End Sub
答案 0 :(得分:4)
快速修复
向后循环。
此外,您不需要I = I + 1,因为这是自动完成的。
Sub DeleteRowBasedOnDateRange()
Dim spem As Workbook
Dim ws As Worksheet
Dim N As Long, I As Long
Set spem = Excel.Workbooks("SwitchP.xlsm")
Set ws = spem.Worksheets("data")
N = ws.Cells(ws.Rows.count, "A").End(xlUp).row
For I = N to 2 Step -1
If ws.Cells(I, "A").Value < Date Then
ws.Rows(I).Delete
End If
Next I
End Sub