I wrote two lines of simple VBA codes to read from and write a date to a cell, but unexpectedly the month and day swapped after the run. The steps are:
Enter a date "1/11/2017" in the cell A1. The date is now displayed as "01/11/2017".
Run the following lines of code:
Dim s As String s = Cells(1, 1).value Cells(2, 1).value = s
The cell B1 now displays "11/01/2017" with the month and day swapped.
My short date format setting in Region in Windows is "dd/MM/yyyy" so the string s stores the value "01/11/2017". However, when writing to the cell, Excel implicitly converts the string s to a date assuming "mm/dd/yyyy" without following the date format setting in Region. I tried to use different short date format settings but that does not change the way Excel converts the string.
So my question is: what could explain the swapping of the day and month? What controls how Excel reads the date string and write to the cell?
s = Cells(1, 1).value
will store thevalue
of the cell in aString
. Not what it shows in the cell.For example
If your cell has
11/1/2017
but is formatted to show01/11/17
thens
will store11/1/2017
. This is not a date. It is aString
. If you do not believe me then try thisNow try this
==> When you are trying to store a
String
which contains a date to a cell which hasGeneral
format then Excel will convert the string to date in a format what it feels is best (based on regional settings). And this is what is happening in your case.Resolution:
1
Declare aDate
variable and then store the value in that. Ex:Dim s As Date
OR
2
Convert the string to a date and then store it. Excel will not change it. And that is whatDateValue(s)
does.Some Testing
Let's take these 3 scenarios
Screenshot