如何将Excel文本转换为日期和时间

时间:2015-08-11 21:10:15

标签: excel-vba vba excel

我的一个Excel列包含如下数据:2/15/2011 2:00:00 AM。我需要将它转换为两列:日期和时间。我尝试了CdateDateValue,左边的函数都给出了类型不匹配错误。请帮忙。

1 个答案:

答案 0 :(得分:0)

将一个DateTime字符串转换为2个单独的字符串:

Public Sub splitDateTime()

    Dim d As String, t As String

    d = DateValue("2/15/2011 2:00:00 AM")
    t = TimeValue("2/15/2011 2:00:00 AM")

    MsgBox d    '"2/15/2011"  (result format varies based on Regional Settings)
    MsgBox t    '"2:00:00 AM"

End Sub

将包含DataTime字符串的列中的所有单元格转换为2列,但标题除外:

Option Explicit

Public Sub splitDateTime()
    Dim str As String, cel As Range, ws As Worksheet, lr As Long

    Set ws = ActiveSheet
    lr = ActiveSheet.UsedRange.Rows.Count

    Application.ScreenUpdating = False
    For Each cel In ws.Range("C1:C" & lr)
        If cel.Row = 1 Then
            With cel
                .Value2 = "Date"
                .Offset(0, 1).Value2 = "Time"
            End With
        Else
            str = cel.Value2
            With cel
                .Value2 = Format(DateValue(str), "ddd, mmm dd yyyy")
                .Offset(0, 1).Value2 = Format(TimeValue(str), "hh:mm:ss AmPm")
            End With
        End If
    Next
    ws.Range("C1:D" & lr).EntireColumn.AutoFit
    Application.ScreenUpdating = True
End Sub