如何根据单元格中的条件删除行

时间:2019-05-17 15:19:36

标签: excel vb.net

我正在尝试自动进行一些日期过滤工作。 如果行不在此时间戳之内,我想删除

2:00 am-10:00 am

因此,如果时间在2:00 am之前或10:00 am以后,请删除整行。 有很多这样的行。

我不太确定从哪里开始,因为我是个初学者,需要一个简单的代码来跟踪。

Here is what the data would look like

2 个答案:

答案 0 :(得分:0)

我的VBA有点生锈,但这应该可以工作

        Sub DelStuff()
        Dim WB As Workbook
        Dim Sheet As Worksheet
        Set WB = ActiveWorkbook
        Set Sheet = WB.ActiveSheet

        For Each r In Sheet.UsedRange.Rows

            If Cells(r.Row, "F").Value <= Date & " " & #2:00:00 AM# Or Cells(r.Row, "F").Value >= Date & " " & #10:00:00 AM# Then
                r.EntireRow.Delete
            End If

        Next r

        End Sub

答案 1 :(得分:0)

这类似于问题https://launchpad.net/~ondrej/+archive/ubuntu/php/+index?batch=75&memo=150&start=150,在该问题中我给出了类似的答案。您可以尝试一下,尽管这假设您的时间采用24小时制,并且假设您只想删除该特定单元格而不是整个行。

Sub TimeDelete()
 'Declare your variables
 Dim timeRng As Range, early As Long, late As Long, lrow As Long 

'Finds the last row with a time in it in Column F
 lrow = ThisWorkbook.Worksheets("Sheet1").Cells(Rows.Count, 6).End(xlUp).Row 

 'Define the times you want to compare against
 early = "02:00:00"
 late = "10:00:00"

 'Specifies the range the times are in
 Set timeRng = ThisWorkbook.Worksheets("Sheet1").Range(Cells(1,6), Cells(lrow,6))

 'Use a For loop to check each value in the range
 For Each Cell In timeRng.Cells
     If TimeValue(Cell.Value) >= TimeValue(early) And TimeValue(Cell.Value) <= TimeValue(late) Then
         Cell.Delete Shift:=xlToLeft 'Deletes cell if it meets the criteria and shifts remaining cells in the row to the left.
     End If
 Next Cell
End Sub