我正在尝试运行一个脚本,该脚本将浏览特定列的所有行。然后,它会将这些列中的日期与设定日期进行比较。如果日期大于删除行。我得到的错误称为编译错误:语法错误。
Sub removewrongyear()
Dim i As Integer
For i = 2 To 635475
If Data.Cells(i,20).Value > DATE(2018,12,31) Then
Rows(i).EntireRow.Delete
Next i
End Sub
答案 0 :(得分:3)
Yuo需要退缩,因为@braX说。指定的数量也超过Integer
变量类型容量。在VBA中,对于ingeter值来说,始终将变量声明为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