简体   繁体   English

在vba中将日期格式从yyyymmdd更改为yyyy / mm / dd

[英]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. 我有WYYYYMMDD的像元值,需要将其转换为YYYY / MM / DD。 actual need is i wan nt to add 7 days to the certain date by using DATEADD functio. 实际需要通过使用DATEADD函数将7天添加到特定日期。 This function have date format of YYYY/MM/DD and my cell value is having date WYYYYMMDD. 该函数的日期格式为YYYY / MM / DD,并且我的单元格值的日期为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: 我不确定WYYYYMMDD中的W是什么,但是如果您可以摆脱它,那么下面的方法应该起作用:

       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. 在Excel中,日期存储为自1900年1月1日以来的天数。因此,今天的日期为43062。这意味着您可以通过公式“ = A1 + 7”将A7中的任何日期添加到单元格A1中的任何7天。需要几天使用DATEADD函数。 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. 因此,如果您的单元格包含一个日期,则只需将其添加7。

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. 日期格式是显示此数字的方式,可以是符号d,m和y的任意组合,并且可以使用范围的NumberFormat属性进行更改。

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. 可以使用DATEVALUE函数将看起来像日期的字符串转换为日期,但前提是该字符串符合已知的Excel日期格式。 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. 在您的情况下,格式YYYYMMDD是一种已知格式,因此,如果是文本,则可以在从开头截去第一个字符后使用它。 So (assuming cell A1) this will put the date 7 days on into variable x: 因此(假设单元格A1),这会将日期7天放到变量x中:

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

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

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