【问题标题】:If a Date is less than a date or a number is less than 1 delete the entire row如果日期小于日期或数字小于 1,则删除整行
【发布时间】:2018-07-26 18:57:06
【问题描述】:

您好,我有下面的床单,我正在尝试清理它,

因此,如果 B 列在 2018 年(2018 年 1 月 1 日)之前或 D 列小于 1,则应删除整行,问题是我的代码正在运行但未满。它不会删除所有符合条件的行,它只会删除一些符合条件的行。

我的代码也是

    Dim wks As Worksheet
    Dim i As Long
    Dim LastRow Aqs Long
    Dim PODate As Date
    Dim THDate As Date

    Worksheets("testPO").Activate
    Set wks = ActiveSheet

    LastRow = wks.Cells(wks.Rows.Count, "A").End(xlUp).Row
    Cells(LastRow, "A").Activate

    For i = 8 To LastRow
        If Cells(i, "D").Value < 1 Or Cells(i, "B") < 43101 Then
            Rows(i).Select
            Selection.Delete Shift:=xlUp 
        End If
    Next i
End Sub

【问题讨论】:

  • 简短回答:向后循环而不是向前循环。 For i = LastRow to 8 Step -1

标签: vba excel date-comparison


【解决方案1】:

向后工作,否则您将跳过行。如果您要删除第 9 行,则第 10 行将成为新的第 9 行。在下一次迭代中,您检查第 10 行,从而跳过已成为第 9 行的原始第 10 行。

Dim i As Long

with Worksheets("testPO")
     For i = .Cells(.Rows.Count, "A").End(xlUp).Row to 8 step -1
         If .Cells(i, "D").Value2 < 1 Or .Cells(i, "B").value2 < 43101 Then
             .Rows(i).entirerow.Delete Shift:=xlUp
         End If
     Next i
end with

【讨论】:

  • 谢谢你能告诉我什么是“with”功能吗?!
  • 为什么是 .Value2 而不是 .Value ?!
  • a) 左边没有任何内容的所有 .Cell 和 .Rows 都属于 Worksheets("testPO")。 b)文本和数字更快,您已经将日期恢复为原始长..
【解决方案2】:

您希望在删除时后退一步不要错过任何内容,因为无论删除如何,循环都会增加变量 i:

If Cells(i, "D").Value < 1 Or Cells(i, "B") < 43101 Then
    Rows(i).Select
    Selection.Delete Shift:=xlUp
    i = i - 1 ' STEP BACK!
End If

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-30
    • 1970-01-01
    相关资源
    最近更新 更多