基于将单元格与用户输入的日期进行比较并跳过空白单元格来删除行

时间:2017-05-09 17:41:07

标签: excel vba excel-vba

我正在寻找一种根据员工的终止日期删除行的方法。我不希望删除空白单元格,因为这些员工仍处于活动状态。我有一个弹出的文本框,询问日期,然后显示输入的日期。然后,它应该在列G中搜索输入日期之前的任何日期并删除这些行,跳过任何空白行。 我一直在寻找一种方法来做到这一点,但我不能让宏停止删除除了标题之外的每一行。日期在G列,它大约有46行,但可以改变。

Sub DateSelectandClean()
    '
    ' DateSelectandClean Macro
    ' User enters date and spreadsheet deletes everything prior to that date, ignoring empty cells.

Application.ScreenUpdating = False

Dim W2Year As Date, N As Long
Dim dt As Date

W2Year = CDate(Application.InputBox(Prompt:="Please enter W2 Year as xx/xx/xxxx Date:", Type:=2))
MsgBox W2Year


N = Cells(Rows.Count, "G").End(xlUp).Row


For i = N To 2 Step -1
dt = Cells(i, 1).Value
    If (Cells(i, 1).Value <> "" And dt < W2Year) Then
        Cells(i, 1).EntireRow.Delete
    End If

Next i
Application.ScreenUpdating = True

End Sub

Sample Data

2 个答案:

答案 0 :(得分:0)

您的代码可能在空白日期出现问题 我将IF分开,以便日期不会继续验证 例如IF "" < #01/01/2017#

尝试这一点,虽然没有太多变化:

Sub DateSelectandClean()

' DateSelectandClean Macro
' User enters date and spreadsheet deletes everything prior to that date, ignoring empty cells.

    Application.ScreenUpdating = False
    Dim dateCol, iRow
    Dim W2Year As Date, N As Long
    Dim dt As String

    W2Year = CDate(Application.InputBox(Prompt:="Please enter W2 Year as dd/mm/yyyy Date:", Type:=2))
    MsgBox W2Year

    N = Cells(Rows.Count, "G").End(xlUp).Row
    dateCol = 7
    For iRow = N To 2 Step -1
        dt = Cells(iRow, dateCol).Value
        If (Cells(iRow, dateCol).Value <> "") Then
            If (CDate(dt) < CDate(W2Year)) Then
                Cells(iRow, dateCol).EntireRow.Delete
            End If
        End If
    Next

    Application.ScreenUpdating = True

End Sub

答案 1 :(得分:0)

主要问题是您在“A”列中查看日期信息,并根据该列进行删除。如果您的日期为“G”,则应检查Cells(x,7),而不是Cells(x,1)

Sub DateSelectandClean()
'
' DateSelectandClean Macro
' User enters date and spreadsheet deletes everything prior to that date, ignoring empty cells.

Application.ScreenUpdating = False

Dim W2Year As Date, lastRow As Long, i As Long, dateCol As Long
Dim dt      As Date

dateCol = 7                  ' for column G

Do While W2Year = "00:00:00"
    W2Year = Format(Application.InputBox(Prompt:="Please enter W2 Year as xx/xx/xxxx Date:", Type:=2), "mm/dd/yyyy")
    MsgBox W2Year
Loop

lastRow = Cells(Rows.Count, dateCol).End(xlUp).Row

For i = lastRow To 2 Step -1
    'If Cells(i, dateCol).Value <> "" Then
    If IsDate(Cells(i,dateCol)) Then
        dt = CDate(Format(Cells(i, dateCol).Value, "mm/dd/yyyy"))
        If dt <= W2Year Then
            Cells(i, dateCol).EntireRow.Delete
        End If
    End If
Next i
Application.ScreenUpdating = True
End Sub

我还将变量从Date更改为String,这样可以在用户输入信息时捕获一些错误。如果你愿意,你可以编辑回来,我只想到有人输入“错误”或格式错误的信息。