简体   繁体   English

VBA更改日期格式

[英]VBA to change the format of date

I have a column V which contains date in dd/mm/yyyy format. 我有一列V ,其中包含dd/mm/yyyy格式的日期。 However, system format shows it as mm/dd/yyyy . 但是,系统格式将其显示为mm/dd/yyyy I want to convert the date format from dd/mm/yyyy to dd-mmm-yyyy . 我想将日期格式从dd/mm/yyyydd-mmm-yyyy

ThisWorkbook.Sheets(1).Range("W" & i).NumberFormat = "dd-mmm-yyyy"

When I convert it using the above code, it changes the value from 08/02/2017 to 02-Aug-2017 . 当我使用上述代码转换时,它将值从08/02/2017更改为02-Aug-2017 It should change to 08-Feb-2017 . 它应该更改为08-Feb-2017 Please assist. 请协助。

Start from the very beginning and try to simplify everything. 从一开始就尝试简化一切。 8.Feb.2017 is the 42774th day in the Excel system. 2017年2月8日是Excel系统中的第42774天。 Thus, in an empty sheet run the following and check the results: 因此,在空白表中运行以下命令并检查结果:

Option Explicit

Public Sub TestMe()

    [a1] = 42774 '08-Feb-17
    [a2] = [a1]
    [a3] = [a1]
    [a4] = [a1]

    [a2].NumberFormat = "dd-mmm-yyyy"
    [a3].NumberFormat = "mmm-dd-yyyy"
    [a4].NumberFormat = "dd-mm-yyyy"

End Sub

In Excel, day 1 is 1-Jan-1900. 在Excel中,第1天是1900年1月1日。 In VBA day 1 is 31-Dec-1899. 在VBA中,第1天是1899年12月31日。

There is nothing wrong with your code. 您的代码没有错。 You have entered "08/02/2017" - This is interpreted as input in the format of "mm/dd/yyyy". 您输入了“ 08/02/2017”-这被解释为“ mm / dd / yyyy”格式的输入。 As a result, the cell is showing "02-Aug-2017". 结果,该单元格显示“ 02-Aug-2017”。

You must change your system date format to read the input (08/02/2017) as date value with format "dd/mm/yyyy". 您必须更改系统日期格式,才能以格式“ dd / mm / yyyy”的形式读取输入(08/02/2017)作为日期值。 After that your cell will show you the date in desired format & value (08-Feb-2017). 之后,您的单元格将以所需的格式和值向您显示日期(08-Feb-2017)。

To change the system date format, go to Control Panel > Region & Language. 要更改系统日期格式,请转到控制面板>区域和语言。 Your current format must be "English (United States)" [or something with mm/dd/yyyy date format]. 您当前的格式必须为“英语(美国)” [或带有mm / dd / yyyy日期格式的内容]。 Change it to "English (United Kingdom)". 将其更改为“英语(英国)”。

This should take care of your problem. 这应该解决您的问题。

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

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