简体   繁体   中英

change the date format from yyyymmdd to yyyy/mm/dd in vba

I have cell value which is of WYYYYMMDD and this needs to be converted to YYYY/MM/DD. actual need is i wan nt to add 7 days to the certain date by using DATEADD functio. This function have date format of YYYY/MM/DD and my cell value is having date WYYYYMMDD.

I'm not sure what the W is in the WYYYYMMDD, but if you can get rid of it then the following should work:

       x.Value = DateSerial(Left(x.Value, 4), Mid(x.Value, 5, 2), Right(x.Value, 2))
       x.NumberFormat = "yyyy/mm/dd"

I think there's some confusion here. In Excel a date is stored as the number of days since the first of January 1900. So today's date is 43062. This means that you can add 7 days to any date in cell A1 by the formula "=A1+7" There is no need to use the DATEADD function for days. Similarly, a function that requires a date doesn't care about the format - it expects a numeric value. So if your cell holds a date you can just add 7 to it.

The date format is the way you show this number and can be any combination of the symbols d, m, and y, and can be changed using the NumberFormat property of a range.

Where confusion arises is that it is possible to enter text that looks like a date, but that isn't actually a date. A string that looks like a date can be converted into a date by using the DATEVALUE function, but only when the string conforms to a known Excel date format. In your case the format YYYYMMDD is a known format, so if it's text you can use this, after chopping off the first character from the front. So (assuming cell A1) this will put the date 7 days on into variable x:

    Dim r as Range
    Dim x as date
    Set r = range("a1")
    x = DateValue(right(r,len(r)-1))+7

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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