Excel VBA从string中获取date

如果我有一个单元格如下:

Tuesday, April 16th 2009 

如何将该string转换为Excel识别的date格式。 我想我必须使用MID()和FIND()函数。

这是一个可以从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 

假设文本在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))