Excel:根据单元格值检查时差

时间:2013-04-07 19:32:33

标签: excel excel-vba vba

我在excel中有两列:

BoxA1000 | 7/4/2013 15:00:43 - User
BoxA1001 | 7/4/2013 15:01:43 - User
BoxA1002 | 7/4/2013 15:02:43 - User
BoxA1003 | 7/4/2013 15:03:43 - User
BoxA1000 | 7/4/2013 15:04:43 - User

并且对于我想要查找的每一行,如果有前一行,其第一列的单元格包含相同的值(BoxA1000),然后查看第二列单元格的时差是多少,并将其放在新单元格中在第三排。

对于上面的示例,我希望结果为

BoxA1000 | 7/4/2013 15:00:43 - User | NO previous entry
BoxA1001 | 7/4/2013 15:01:43 - User | NO previous entry
BoxA1002 | 7/4/2013 15:02:43 - User | NO previous entry
BoxA1003 | 7/4/2013 15:03:43 - User | NO previous entry
BoxA1000 | 7/4/2013 15:04:43 - User | 00:04:00 (or) 4 minites (or) something like that

我怎么能用宏来做到这一点?

1 个答案:

答案 0 :(得分:0)

其他假设:没有列标题,数据范围连续并且在Range("A1")中开始,任何A列条目只有一个可能的重复。

Sub test_Solution()

Dim arrBox As Variant
    arrBox = Range(Range("A1"), Range("B1").End(xlDown))
Dim boFound As Boolean

Dim i As Long, j As Long
For i = 1 To UBound(arrBox, 1)
    For j = 1 To i
        If arrBox(i, 1) = arrBox(j, 1) And i <> j Then
            'here we found
            Cells(i, 3) = Format(arrBox(j, 2) - arrBox(i, 2), "h:m:s")
            boFound = True
            Exit For
        End If
    Next j
    If Not boFound Then Cells(i, 3) = "No previous entry"
    boFound = False
Next i
End Sub