1

所以这是我的场景:

我有一个 Cisco 登录和注销报告,可以将我的数据导出到 Excel 中。伟大的!唯一的问题是它在一天内给了我多次登录时间,所以我试图只进行第一次登录尝试,然后在那天把其余的都扔掉,然后转到下一天。

该单元格由 Cisco 预先格式化为m/d/yyyy" "h\:mm\:ss AM/PM. 我正在自学 VBA,我想从该单个单元格中获取 m/d/yyyy,并将其与其他单元格进行比较。如果日期存在,我想删除这些行。

例子:

5/2/2012 2:55:12PM
5/2/2012 3:00:00PM
5/2/2012 3:01:00PM
5/3/2012 2:56:01PM

我想删除 for 循环中的第二个和第三个条目。

如果不清楚,请告诉我,非常感谢您的帮助!

4

1 回答 1

1

您提到preformatted by Cisco as m/d/yyyy" "h\:mm\:ss AM/PM.上面的示例与该格式不匹配。您提供的样品应该是

5/2/2012 2:55:12 PM
5/2/2012 3:00:00 PM
5/2/2012 3:01:00 PM
5/3/2012 2:56:01 PM

即前面有一个空格PM

下面的代码示例基于格式m/d/yyyy h\:mm\:ss AM/PM

代码

Sub Sample()
    Dim ws As Worksheet
    Dim lRow As Long, i As Long
    Dim delRange As Range

    '~~> Set this to the sheet where you have the data
    Set ws = Sheets("Sheet1")

    With ws
        '~~> Sort the data in ascending order
        .Range("A:A").Sort key1:=.Range("A1"), order1:=xlAscending

        '~~> Get the last row
        lRow = .Range("A" & .Rows.Count).End(xlUp).Row

        '~~> loop through the cells
        For i = 2 To lRow
            '~~> Check if date matches
            If Application.Evaluate("=DATE(YEAR(A" & i & "),MONTH(A" & i & "),DAY(A" & i & "))") = _
            Application.Evaluate("=DATE(YEAR(A" & i - 1 & "),MONTH(A" & i - 1 & "),DAY(A" & i - 1 & "))") Then
                '~~> Check if the value is greater
                If .Range("A" & i).Value > .Range("A" & i - 1).Value Then
                    '~~> identify cells to delete
                    If delRange Is Nothing Then
                        Set delRange = .Range("A" & i)
                    Else
                        Set delRange = Union(delRange, .Range("A" & i))
                    End If
                End If
            End If
        Next i

        '~~> Delete cells
        If Not delRange Is Nothing Then delRange.Delete
    End With
End Sub

截屏

在此处输入图像描述

于 2012-08-05T23:43:25.563 回答