如果满足2个条件,则删除行 – 在另一列中更改时间和相同的值

我想在excel vba中编写一个循环来执行以下操作:

我有一个很长的date+时间的专栏。 我有另一列有一个文本string。

我想删除整个行,如果时间的变化(上面的行 – 行)小于0:00:05和string的值是相同的(上面的行vs行)

我遇到了中频条件的问题,特别是5秒的部分,它不喜欢它…

For Lrow = Lastrow To Firstrow Step -1 'We check the values in the D column With .Cells(Lrow, "D") If Not IsError(.Value) Then If (Cells(i,"D") - Cells(i-1,"D")) > (0:00:05) AND (Cells.Value(i,"F") = Cells.Value(i-1,"F") Then .EntireRow.Delete End If End With Next Lrow 

好的,上面的代码很烂。 我要去探索一个不同的方法。 我想比较列F – 与当前单元格下面的一个。 如果它们相同,则触发下一个子句 – 查看D中的当前单元格是否与下面的单元格不同,如果是,则删除(或存储要在循环外部删除的信息)。

如果F中的两个单元格不相同,则跳到下一个单元格。

这更有意义? 让我编写代码并将其发布到此处。

您的时间将需要表示为一个数字,因为Excel中的date计算为自给定date以来的天数(例如,今天是从1900年1月1日起的41458天)。 所以,一天24小时,一小时,然后12分钟,例如5分钟:

EDITED

改变其他因素以及时间比较,我已经在下面的评论中重新编写了代码。

下面的代码是一个如何使这个macros自动删除添加新行的例子。 应该将代码添加到您正在进行更改的工作表(而不是模块或工作簿)上。 如果你不想采取自动的方法,那么你可以添加一个选项,先检查用户,或者只是改变子,并传入一个范围对象代表一个刚添加的行的单元格(让我知道如果你需要帮助这个):

 Private Sub Worksheet_Change(ByVal Target As Range) Dim newStr Dim newDate Dim prevStr Dim prevDate Dim interval newStr = Range("D" & Target.Row).Value newDate = Range("F" & Target.Row).Value prevStr = Range("D" & Target.Row - 1).Value prevDate = Range("F" & Target.Row - 1).Value interval = (1 / 24) / 12 ' 5 mins If newStr = prevStr And Abs(newDate - prevDate) <= interval Then Target.EntireRow.Delete End If End Sub 

我已经build立了一些testing数据,上面的代码似乎可以很好地处理我设置的样本数据,如果您有任何问题,请告诉我们。

我看到各种问题,包括一些似乎并不正确的指标。 在这里,你有一个改进的版本(循环正在转发,因为它似乎更清楚):

  Dim toDelete(10) As Integer 'Put same size than Lastrow rather than 10 Dim toDeleteCount As Integer: toDeleteCount = -1 'FirstRow has to be greater or equal than 2 Firstrow = 2 For Lrow = Firstrow To Lastrow Step 1 'We check the values in the D column With Cells(Lrow, "D") If Not IsEmpty(.Value) Then If ((CDate(Cells(Lrow, "D")) - CDate(Cells(Lrow - 1, "D")) > CDate("0:00:05")) And (Cells(Lrow, "F") = Cells(Lrow - 1, "F"))) Then Cells(Lrow, "D") = "" Cells(Lrow, "F") = "" 'You cannot delete the whole row inside the loop. Just delete the values in the cells you want or store the row number in a variable such that you can delete all the rows outside the loop toDeleteCount = toDeleteCount + 1 toDelete(toDeleteCount) = Lrow End If End If End With Next Lrow If (toDeleteCount >= 0) Then For Each rDelete In toDelete Rows(rDelete).Delete Next rDelete End If 

好的,所以经过多一点挖掘,我发现这个并修改它的工作。

感谢你的帮助Varocarbas和Chris!

 Sub deleterows() Dim myrange, mycell As Range Dim myrow() Set myrange = Sheets("sheet5").Range("F2", Range("F" & Rows.Count).End(xlUp)) For Each mycell In myrange If mycell.Value = mycell.Offset(-1, 0).Value Then If mycell.Offset(0, -2).Value - mycell.Offset(-1, -2).Value <= TimeValue("00:00:05") Then q = q + 1 ReDim Preserve myrow(q) myrow(q) = mycell.Row End If End If Next mycell For i = q To 1 Step -1 p = myrow(i) myrange(p - 1, 1).EntireRow.Delete Next i End Sub