【发布时间】:2021-02-11 23:30:39
【问题描述】:
我想过滤一个名为“Vessel Estimated Time of Arrival”的列,并删除所有未来日期的数据。
例如,今天的日期 2020 年 11 月 13 日。检查并删除所有未来日期的数据,并保留 2020 年 11 月 13 日之前的所有数据。
此宏执行没有错误,但不会删除 2021 年的数据。
Sub Sort_ETAPOD()
Dim wb As Workbook
Dim sRng As Range
Dim fRng As Range
Dim cel As Range
Dim tRow As Long
Dim fCol As Long
Dim tmDate As String
Set wb = ThisWorkbook
Set fRng = ActiveWorkbook.Worksheets("POD").Rows(1).Find(what:="Vessel Estimated Time of Arrival", LookIn:=xlValues, lookat:=xlWhole)
fCol = fRng.Column
tRow = ActiveWorkbook.Worksheets("POD").Cells(Rows.Count, 1).End(xlUp).Row
With ActiveWorkbook.Worksheets("POD")
Set sRng = .Range(.Cells(2, fCol), .Cells(tRow, fCol))
End With
'Date format MM-DD-YYYY
tmDate = Format(Date, "mm/dd/yyyy")
'performs a cell loop value to check for "vessel (...) departure..."
For Each cel In sRng
If Trim(Format(cel.Value, "mm/dd/yyyy")) >= tmDate Then
'marks any date greater than today() date with an "y"
cel.Value = "y"
Else
End If
Next cel
Set sRng = Nothing
With wb.Sheets("POD")
Set sRng = .Range(.Cells(1, fCol), .Cells(tRow, fCol))
End With
'function deltR will remove any cel in found col with has "y" value, where "y" equals to cells that had date greater than DATE() (today)
'passing arguments: range (sRng), delete anything not empty, on col#1 (sRng has only one range = columns("U:U" + tRow)
Call deltpod(sRng, "y", 1)
End Sub
Private Sub deltpod(ByRef sRng As Range, ByVal aStr As String, ByVal f As Integer)
Dim wb As Workbook '---This Relates to (Vessal Estimated time of arrival event)----
'this sub procedure looks for a string (aStr) passed in (sRng) range object range, based on col number (f)
With sRng
.AutoFilter Field:=f, Criteria1:=aStr
.Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete
End With
ActiveWorkbook.Worksheets("POD").AutoFilterMode = False
Set sRng = Nothing
End Sub
【问题讨论】:
-
您是否将日期与字符串进行比较?逐步检查您的代码并查看是否填充了任何“y”。我的猜测是你把你的数据类型弄混了,你试图比较一个字符串类型和一个日期类型,它们是两个不同的东西。
-
不明白你的意思。
-
你有 Dim tmDate As String,它创建了一个日期的文本字符串。这与您在工作表中的内容完全不同(这是格式化为日期的日期的数字表示)。看看这是否有帮助:stackoverflow.com/questions/17163982/…
-
我自己会使用自动过滤器,但是对于您的方法,我建议不要使用字符串,而是比较基础值。例如,将比较行更改为
If Int(cel.Value2) >= CDbl(Date) then ...