简体   繁体   English

Excel VBA将字符串日期转换为实际日期

[英]Excel VBA Convert String Date to a real date

I'm using the following code but for some reason the second line isn't converting it into a real date. 我正在使用以下代码,但由于某种原因,第二行未将其转换为实际日期。

DateStr = Replace(DateStr, "-", "/")
DateStr = Format(CDate(DateStr), "dd/mm/yyyy")
DateStr = DateStr + 1

Even if I do: 即使我这样做:

Dim RealDate As Date

DateStr = Replace(DateStr, "-", "/")
RealDate = Format(CDate(DateStr), "dd/mm/yyyy")
RealDate = RealDate + 1

As you can see from line 3, I am trying to +1 to the day which could also change the month or year potentially. 正如您从第3行看到的那样,我正在尝试将+1调整为当天,这也可能会更改月份或年份。

You are having trouble identifying just where you should be adding 1 to the date. 您在确定应该在日期上加1的位置时遇到了麻烦。 Try, 尝试,

DateStr = Format(CDate(DateStr) + 1, "dd/mm/yyyy")

The CDate conversion function is where you get the numerical date vaue that will accept the addition of another day. CDate转换功能是您获取数字日期值的地方,它将接受另一天的增加。

Second one works OK for me: 第二个对我有效:

Sub Tester()

    Dim RealDate As Date, DateStr As String

    DateStr = "7-20-2015"

    DateStr = Replace(DateStr, "-", "/")
    RealDate = Format(CDate(DateStr), "dd/mm/yyyy")
    RealDate = RealDate + 1

    Debug.Print RealDate '>> 7/21/2015

End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM