VBA 将字符串转换为日期格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20672875/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 01:01:46  来源:igfitidea点击:

VBA convert string to date format

excelvbadate

提问by SeekingAlpha

I have a file with strings that are in the format YYMMDD. eg. 120216 (will always be in this format).

我有一个包含格式为 YYMMDD 的字符串的文件。例如。120216(将始终采用此格式)。

I want to convert this into a date ideally in the format DDMMYY or DDMMYYYY.

我想将其理想地转换为 DDMMYY 或 DDMMYYYY 格式的日期。

Has anyone come across a similar problem and how did they resolve it?

有没有人遇到过类似的问题,他们是如何解决的?

回答by Siddharth Rout

You can split the string and then use DateSerial. See this example.

您可以拆分字符串,然后使用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

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

谢谢,我可能不得不写一个函数,我可以在其中传递字符串日期以进行转换。有没有可能将 Debug... 行保存到变量中?(似乎不能)或替代解决方法?– 马可·苏西洛 4 分钟前

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