您可以拆分字符串,然后使用DateSerial。请参阅此示例。
Option Explicit
Sub Sample()
Dim sDate As String
Dim Y As Long, M As Long, D As Long
sDate = "120216"
Y = Left(sDate, 2)
M = Mid(sDate, 3, 2)
D = Right(sDate, 2)
Debug.Print Format(DateSerial(Y, M, D), "DDMMYY")
Debug.Print Format(DateSerial(Y, M, D), "DDMMYYYY")
End Sub
来自 cmets 的跟进
谢谢,我可能不得不编写一个函数,我可以在其中传递字符串日期以进行转换。是否有机会将 Debug... 行保存到变量中? (似乎不能)或替代工作? – Marco Susilo 4 分钟前
我没有进行任何错误处理。我确定你可以解决这个问题?
Option Explicit
Sub Sample()
Dim Ret As String
Ret = GetDate("120216", "DDMMYY")
Debug.Print Ret
Ret = GetDate("120216", "DDMMYYYY")
Debug.Print Ret
End Sub
Function GetDate(sDate As String, sFormat As String) As String
Dim Y As Long, M As Long, D As Long
Y = Left(sDate, 2)
M = Mid(sDate, 3, 2)
D = Right(sDate, 2)
GetDate = Format(DateSerial(Y, M, D), sFormat)
End Function