首页 > 解决方案 > 将存储为文本的 AM/PM 时间转换为军用时间

问题描述

我有数百行的 Excel 表格报告,在其中一个单元格中,我将时间值存储为 AM/PM。

问题是单元格值作为文本值存储,我无法更改它,因为它是从系统生成的。我需要按时间对工作表进行排序才能对其进行处理,但问题是,例如 01:00 PM 将在 09:00 AM 或 08:00 AM 之前出现,等等。

现在我有一些代码可以解决这个问题:

Sub DepTime()
'12:00 AM
With Range("D1:D1000")
    Set c = .Find("12:00 AM", LookIn:=xlValues)
    If Not c Is Nothing Then
        firstAddress = c.Address
        Do
            c.Activate
            c.Value = "00:00"
            Set c = .FindNext
            If c Is Nothing Then
                GoTo SearchTime2
            End If
        Loop While Not c Is Nothing And c.Address <> firstAddress
    End If
SearchTime2:
End With
'12:15 AM
With Range("d1:d1000")
    Set c = .Find("12:15 AM", LookIn:=xlValues)
    If Not c Is Nothing Then
        firstAddress = c.Address
        Do
            c.Activate
            c.Value = "00:15"
            Set c = .FindNext
            If c Is Nothing Then
                GoTo SearchTime3
            End If
        Loop While Not c Is Nothing And c.Address <> firstAddress
    End If
SearchTime3:

... Code goes like this all the way to 11:45pm...

End With
End Sub

代码一直到晚上 11 点 45 分……我花了几个小时来做​​这件事;它有帮助,但必须有更好的方法......另外,我只有 15 分钟间隔的代码,但如果我得到一个特定的时间,比如下午 1:13,它对我没有帮助......有没有一种将任何给定时间从文本转换为军事时间的方法......

任何帮助将不胜感激。

标签: excelvbaexcel-formula

解决方案


更改@braX 提到的格式,然后一次性.TextToColumns格式化整个范围/列。不需要循环。

在下面的示例中,我假设数据位于 Sheet1 的 Col A 中。根据需要进行更改。

With Sheet1
    With .Columns(1)
        .NumberFormat = "hh:mm"
        .TextToColumns Destination:=Sheet1.Range("A1"), DataType:=xlDelimited, _
        TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
        Semicolon:=False, Comma:=False, Space:=False, Other:=False, FieldInfo _
        :=Array(Array(1, 1), Array(2, 1)), TrailingMinusNumbers:=True
    End With
End With

顺便说一句,您不需要 VBA。您只需单击几下鼠标即可完成相同的操作,如下所示。

在此处输入图像描述


推荐阅读