excel宏删除额外的行

时间:2014-02-18 00:51:32

标签: excel vba excel-vba

我有一个宏可以删除excel中我不想要的行。它会删除在上午9:30之前和下午4:00之后有时间的行。出于某种原因,它还删除时间为上午10:00至上午10:09,上午11:00至上午11:09,中午12:00至下午12:09,下午1:00至1的行:晚上9点,下午2点到2点09分,下午3点到3点09分

请帮助我,这样就不会删除这些行。

我的代码:

Sub DeleteRows()

Dim lastRow As Long
Dim Cell As Long
Dim dt As Date

'Work with the active sheet.
With ActiveSheet

    'Find the last row of your dataset.
    lastRow = .Range("A:A").Find("*", searchdirection:=xlPrevious).Row

    'Format your time column to a readable time.
    .Columns("B").NumberFormat = "[$-F400]h:mm:ss AM/PM"

    'Loop through the rows, beginning at the bottom.
    For Cell = lastRow To 2 Step -1

        'Piece together the date.
        dt = Mid(.Cells(Cell, 1), 5, 2) & "/" & _
             Mid(.Cells(Cell, 1), 7, 2) & "/" & Left(.Cells(Cell, 1), 4)

        'If the date is a Sat or Sun, delete the row.
        If Weekday(dt) = 1 Or Weekday(dt) = 7 Then
            .Rows(Cell).EntireRow.Delete

        'If the time is before 9:30am or after 4pm, delete the row.
        ElseIf CInt(Hour(.Cells(Cell, 2)) & Minute(.Cells(Cell, 2))) < 930 Or _
    CInt(Hour(.Cells(Cell, 2)) & Minute(.Cells(Cell, 2))) > 1600 Then
            .Rows(Cell).EntireRow.Delete
        End If
    Next Cell
End With

MsgBox "Done!"

2 个答案:

答案 0 :(得分:1)

而不是使用

CInt(Hour(.Cells(Cell, 2)) & Minute(.Cells(Cell, 2)))

使用

100*Hour(.Cells(Cell, 2)) + Minute(.Cells(Cell, 2))

你正在解决你的问题,因为,例如,11:08被转换为11小时8分钟,当你的代码连接在一起时产生118(满足删除条件小于930)。修订版(未经测试)应将其转换为1108并避免满足删除条件。

答案 1 :(得分:1)

您可以尝试根据实际的time检查值:

    'If the time is before 9:30am or after 4pm, delete the row.
      ElseIf .Cells(Cell, 2) - Int(.Cells(Cell, 2)) < CDate("09:30:00") Or _
         .Cells(Cell, 2) - Int (.Cells(Cell, 2)) > CDate("16:00:01") Then
     .Rows(Cell).EntireRow.Delete

注意上限16:00:01避免了16:00:00处的边界评估错误(可能是由于四舍五入)。