Excel VBA从字符串中获取日期

时间:2012-10-18 20:17:53

标签: excel vba

如果我有一个包含以下内容的单元格:

Tuesday, April 16th 2009

如何将该字符串转换为Excel识别的日期格式。我想我必须使用MID()和FIND()函数。

2 个答案:

答案 0 :(得分:5)

这是一个可以在VBA和用户定义函数

中运行的函数
Function GetDate(InString As Range) As Date
    Dim newDate As Date
    Dim tmpDate As String

    'Sample Date
    'Tuesday, April 16th 2009

    'Remove the Day of the Week.
    tmpDate = Trim(Mid(InString, InStr(InString, ",") + 1))

    'Get rid of "th"
    tmpDate = Replace(tmpDate, "th ", " ")

    'Get rid of "rd"
    tmpDate = Replace(tmpDate, "rd ", " ")

    'Get rid of "nd"
    tmpDate = Replace(tmpDate, "nd ", " ")

    'Get rid of "st"
    tmpDate = Replace(tmpDate, "st ", " ")

    'Convert string to date
    newDate = DateValue(tmpDate)

    GetDate = newDate
End Function

答案 1 :(得分:0)

假设文本在A1中,我们可以将其分解为单独的部分,并使用DATEVALUE将其组合在一起。

B1: =MID(A1,FIND(" ",A1)+1,FIND(" ",A1,FIND(" ",A1)+2)-FIND(" ",A1))
B2: =IFERROR(VALUE(MID(A1,FIND(" ",A1,FIND(" ",A1)+2),3)),VALUE(MID(A1,FIND(" ",A1,FIND(" ",A1)+2),2)))
B3: =RIGHT(A1,4)
B4: =DATEVALUE(B2&" "&B1&" "&B3)

或者,您可以一次性完成:

=DATEVALUE(IFERROR(VALUE(MID(A1,FIND(" ",A1,FIND(" ",A1)+2),3)),VALUE(MID(A1,FIND(" ",A1,FIND(" ",A1)+2),2)))&" "&MID(A1,FIND(" ",A1)+1,FIND(" ",A1,FIND(" ",A1)+2)-FIND(" ",A1))&" "&RIGHT(A1,4))