简体   繁体   中英

VBA to change the format of date

I have a column V which contains date in dd/mm/yyyy format. However, system format shows it as mm/dd/yyyy . I want to convert the date format from dd/mm/yyyy to dd-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 . It should change to 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. 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. In VBA day 1 is 31-Dec-1899.

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". As a result, the cell is showing "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". After that your cell will show you the date in desired format & value (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]. Change it to "English (United Kingdom)".

This should take care of your problem.

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