在Excel中删除包含特定时间的行

时间:2018-04-24 02:22:10

标签: excel vba delete-row

我在Excel中对约会记录进行排序,并希望在上午9点之前删除包含约会时间的行(当前存储在B列中),但暂时保留空白单元格。我尝试过运行以下代码,但它给了我一个语法错误。我错过了什么?

Sub ApptTime()
Dim lr As Long, i As Long

lr = Cells(Rows.Count, "B").End(xlUp).Row

For i = lr To 1 Step -1
    If IsNumeric(Cells(i, "B")) And _
    (Cells(i, "B").Value < TimeSerial(9, 0, 0)  And _
    (Cells(i, "B").Value <> ""     Then
       Rows(i).EntireRow.Delete
    End If
End Sub

2 个答案:

答案 0 :(得分:0)

您在Next i之前遗漏了End Sub,并且您有一些需要删除的流氓括号。

Sub ApptTime()
    Dim lr As Long, i As Long

    lr = Cells(Rows.Count, "B").End(xlUp).Row

    For i = lr To 1 Step -1
        If IsNumeric(Cells(i, "B")) And _
         Cells(i, "B").Value2 < TimeSerial(9, 0, 0)  And _
         Cells(i, "B").Value2 <> ""     Then
           Rows(i).EntireRow.Delete
        End If
    next i
End Sub

答案 1 :(得分:0)

另一种方法,只循环遍历数字单元格并跳过空白:

Sub ApptTime()
    Dim iArea As Long, iCell As Long

    With Range("B1", Cells(Rows.count, "B").End(xlUp)).SpecialCells(xlCellTypeConstants, xlNumbers) ' reference column B cells from row 1 down to last not empty one with "numeric" content only
        For iArea = .Areas.count To 1 Step -1 ' loop through referenced range "Areas" from the last one backwards
            For iCell = .Areas(iArea).count To 1 Step -1 'loop through current area cells form the last one backwards
                With .Areas(iArea).Cells(iCell, 1) 'reference current cell in current area
                    If IsNumeric(.Value) And .Value < TimeSerial(9, 0, 0) And .Value <> "" Then .EntireRow.Delete
                End With
            Next
        Next
    End With
End Sub