如何将20120103之类的数字转换为Excel可识别的日期?

时间:2012-06-18 18:58:08

标签: excel vba datetime

我有一个8位数字告诉我日期,YYYYMMDD。如何将此数字转换为Excel将识别为日期的日期。

我们假设单元格A1中有20120229 ...我该怎么办?

3 个答案:

答案 0 :(得分:6)

由于你标记了这个问题VBA,我假设你想在VBA中得到答案,所以你走了:

Dim l As Long
Dim s As String
Dim d As Date

l = Range("A1").Value ' 20120229

' convert it to a string 
s = CStr(l)

' can now use string functions to parse it
d = DateSerial(CInt(Left(s, 4)), CInt(Mid(s, 5, 2)), CInt(Right(s, 2)))
' d is now 29 Feb 2012

' write it back to the sheet
Range("A2").Value = d

答案 1 :(得分:4)

使用此公式:=DATE(LEFT(A1,4),MID(A1,5,2),RIGHT(A1,2))其中A1是单元格坐标。

答案 2 :(得分:1)

我希望能够在Excel中选择文本并调用宏来完成工作。

Sub YYYYMMDDToDate()
 Dim c As Range
 For Each c In Selection.Cells
  c.Value = DateSerial(Left(c.Value, 4), Mid(c.Value, 5, 2), Right(c.Value, 2))
  'Following line added only to enforce the format.
  c.NumberFormat = "mm/dd/yyyy"
 Next
End Sub
相关问题