正如@braX 所说,你需要后退一步。还指定数量超过Integer
可变类型容量。在 VBA 中,整数值始终将变量声明为Long
.
范围“数据”未设置。我参考活动工作表替换了它。
变量 YearA 也未指定。我给它分配了2018年的值。日期函数使用不正确,您的意思是使用 DateSerial。
总是放Option Explicit
在代码之上捕获错误。这里真的有很多人。
Option Explicit
Sub removeWrongYear()
Dim i As Long, yearA as Long
yearA = 2018
With ActiveSheet
For i = 635475 to 2 Step -1
If .Cells(i,20).Value > DateSerial(yearA,12,31) Then .Rows(i).EntireRow.Delete
Next i
End With
End Sub
这是一个基于数组的快速版本,一次删除所有行:
Option Explicit
Option Base 1 'row and column index will match array index
Sub removeWrongYear()
Dim i As Long, yearA As Long, rowsCnt As Long
Dim rowsToDelete As Range
Dim vData As Variant
yearA = 2018
With ActiveSheet
'1st to 635475 row, 20th column
vData = Range(.Cells(1, 20), .Cells(635475, 20))
For i = UBound(vData) To 2 Step -1
If vData(i, 1) > DateSerial(yearA, 12, 31) Then
rowsCnt = rowsCnt + 1
If rowsCnt > 1 Then
Set rowsToDelete = Union(rowsToDelete, .Rows(i))
ElseIf rowsCnt = 1 Then
Set rowsToDelete = .Rows(i)
End If
End If
Next i
End With
If rowsCnt > 0 Then
Application.ScreenUpdating = False
rowsToDelete.EntireRow.Delete
Application.ScreenUpdating = True
End If
End Sub