VBA将字符串转换为日期格式 [英] VBA convert string to date format
问题描述
我想将其转换成DDMMYY或DDMMYYYY格式的理想状态。
有没有人遇到一个类似的问题,他们是如何解决的?
你可以拆分字符串,然后使用 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 =右(sDate,2)
Debug.Print格式(DateSerial(Y,M,D),DDMMYY)
Debug.Print格式(DateSerial(Y,M,D),DDMMYYYY)
End Sub
评论后跟
谢谢,我可能要写一个我可以传入的功能字符串日期进行转换。任何将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
函数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 =右(sDate,2)
GetDate = Format(DateSerial(Y,M,D),sFormat)
结束函数
I have a file with strings that are in the format YYMMDD. eg. 120216 (will always be in this format).
I want to convert this into a date ideally in the format DDMMYY or DDMMYYYY.
Has anyone come across a similar problem and how did they resolve it?
You can split the string and then use DateSerial
. See this example.
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
Followup from comments
Thanks, I am probably going to have to write up a function where I can pass in string dates to get converted. Any chance that the Debug... line be saved into a variable? (can't seem to) or an alternative work around? – Marco Susilo 4 mins ago
I have not done any error handling. I am sure you can take care of that?
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
这篇关于VBA将字符串转换为日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!