根据输入框日期删除行

时间:2018-08-16 13:23:19

标签: excel vba excel-vba

我需要有关特定宏的帮助:我有一个excel电子表格,其中“ K”列中有空白单元格和带有日期的单元格。我需要创建一个宏,该宏将删除日期在输入框日期之前的所有行。但是我还需要保持空白。 我尝试了多个在网上找到的示例,但没有任何效果。 请帮忙, 谢谢

2 个答案:

答案 0 :(得分:1)

您可以尝试一下,只需将ws设置为日期所在的任何工作表即可

Sub datechecker()

    Dim inputBoxText As String
    Dim inputBoxDate As Date
    Dim lastRow As Integer
    Dim row As Integer
    Dim ws As Worksheet

    Set ws = ThisWorkbook.Worksheets(1)

    With ws    

    lastRow = .Cells(.Rows.Count, "K").End(xlUp).row
    inputBoxText = InputBox("Please enter a Date:", "Date Input Box", "Type Here", 10, 10)

    If IsDate(inputBoxText) Then
        inputBoxDate = CDate(inputBoxText)
    Else
        MsgBox "Please enter a correct date"
        Exit Sub
    End If

    On Error GoTo Handler
    For row = 1 To lastRow
        If Len(.Range("K" & row).Value) > 0 Then
            If inputBoxDate > CDate(.Range("K" & row).Value) Then
                .Rows(row).EntireRow.Delete
                row = row - 1
            End If
        End If
    Next

    End With

    Exit Sub

Handler:
    MsgBox "Please make sure cells are formatted to date"

End Sub

答案 1 :(得分:0)

以上评论是正确的,下次请提供您到目前为止已经尝试过的内容,而不仅仅是要求我们完成所有工作。

但是,这是我解决此问题的方法: 1)在D2:D24中,我有2016年和2017年12月31日之间的随机日期。假设您要删除日期为01-03-2017之前的所有行。在E列中,我添加了日期值的数值,这意味着01-03-2017 = 42795。 您可以使用下一个宏:

Sub cleardatesmallerthan()
Dim i As Integer
    For i = 1 To 24
      If Sheets(1).Range("e" & i).Value <= 42795 Then
      Sheets(1).Range("D" & i).Value = ""
      End If
    Next i
End Sub