Excel 格式的日期信息无法识别为日期

Date information in a format Excel doesn't recognize as a Date

我有一个来自系统的生成文件,该文件的日期格式是这样的 Mar 28 2016 4:55:54:380PM 我在 VBA 中的脚本无法将其识别为日期或 Excel不将其识别为日期格式,而只是一个字符串。还有别的办法吗?

日期格式不在VBA#MM/DD/YYYYh:mm:ss.sss PM#?

试试这个

Public Function stringtodate(mytext) As Date
    str1 = Split(mytext, " ")
    str2 = UBound(str1)
    If str2 > 2 Then
        If LCase(Left(str1(0), 3)) = "mar" Then
            mon = "03"
        End If
        stringtodate = str1(1) & "-" & mon & "-" & str1(2)
    Else
        'not a valid date
    End If
End Function

您在评论中提到您只需要日期:

Sub dateTest()
    Dim d As Date
    s = "Mar 28 2016 4:55:54:380PM"
    s = Left(s, 11)
    d = DateSerial(Year(s), Month(s), Day(s))
    Debug.Print d
End Sub

28.03.2016

迭代一些数据集:

Sub dateIteration()
    Dim d As Date, v As Variant
    Dim rng As Range

    Set rng = Range("A1:A10")

    For Each r In rng
        v = Left(r.Value, 11)
        d = DateSerial(Year(v), Month(v), Day(v))

        ' Do something with d
        ' Print it to worksheet, maybe?
        r.Value = d
    Next r
End Sub

以最少的代码混乱迭代非连续范围:

Sub helperSub()
    Call dateIteration(Range("A1:A10"))
    Call dateIteration(Range("Z1:Z10"))
    Call dateIteration(Range("H1:M89"))
End Sub

Sub dateIteration(rng As Range)
    Dim d As Date, v As Variant

    For Each r In rng
        v = Left(r.Value, 11)
        d = DateSerial(Year(v), Month(v), Day(v))

        ' Do something with d
        ' Print it to worksheet, maybe?
        r.Value = d
    Next r
End Sub

这是一个 2 行代码 ;)

我假设范围是从 A1:A20。请酌情修改

Sub Sample()
    [A1:A20].NumberFormat = "DD/MM/YYYY"
    [A1:A20] = [index(DATE(MID(A1:A20,8,4),MONTH(1&LEFT(A1:A20,3)),MID(A1:A20,5,2)),)]
End Sub

如果您想了解这段代码的作用,请参阅我给出的解释 Here