excelmacros删除额外的行

我有一个macros,删除我不想在Excel中的行。 它会删除上午9:30之前和下午4:00之后的行。 由于某种原因,它也删除了上午10:00到上午10:09,上午11:00到上午11:09,中午12:00到下午12:09,下午1:00到1: 09:00,下午2:00至2:09,下午3:00至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!" 

您可以尝试检查实际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避免了边界评估错误(可能由于四舍五入)。

而不是使用

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

使用

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

你正在碰到你的问题,因为,例如,11:08正在被转换成11小时8分钟,当你的代码连接在一起时产生118(满足小于930的删除条件)。 修改后的版本(未经testing)应将其转换为1108,并避免符合删除条件。