2
votes

I have written a long procedure in VBA to manipulate a data set. Part of this involves using and formatting dates, and I can't get it to work properly.

The initial data as downloaded has dates in the format "yyyy-mm-ddThh:mm:ssZ" - e.g. 2014-12-11T04:59:00Z.

I then convert these into a date in UK format of "dd/mm/yyyy". Looping over all relevant cells, I use the following method:

initial_date = Range("A1").Value

Dim publish_date As Date

publish_date = DateValue(Mid(initial_date,9,2) & "/" & Mid(initial_date,6,2) & "/" & Mid(initial_date,1,4))

Range("A1").Value = publish_date

This seems to work fine. The cell automatically changes format to "Date" and when I calculate the difference between these dates and dates in another column, it works fine.

I then pick up these dates again and add to an array:

feed(1, 8) = Range("A1")

and then transfer this value into another array:

new_array(7, 1) = feed(1, 8)

Finally, I insert the value from the new array into a different cell. Having used UK date formatting thus far, I now want this value to display in the form "mm/dd/yyyy".

Range("E1") = new_array(7, 1)
Range("E1").NumberFormat = "mm/dd/yyyy"

This is where it goes wrong.

Running the code as above, the dates are all displayed as "dd/mm/yyyy" format. Excel changes the format of the cells to "custom". Finding the difference between these and other dates works, so the data seems to be stored correctly but not displaying as I want.

If I change the code to

Range("E1") = new_array(7, 1)
Range("E1").NumberFormat = "dd/mm/yyyy"

the dates still do not display correctly. Dates which can be written either way around (i.e. day is equal to or less than 12) display correctly, but are in fact the wrong date. i.e. 2014-12-11T04:59:00Z displays as 12/11/2014 which is what I want, but Excel thinks the date is the 12th November instead of 11th December. Dates such as 29/09/2014 which cannot be written both ways round display in UK format, but are not recognised properly by Excel which thinks the long date should be "29/09/2014" instead of "29 September 2014".

When I remove the formatting line completely, the results are the same.

I'm sorry for the rather long-winded explanataion, but there's clearly something I'm not understanding about how Excel and VBA handle, store and format dates. If anyone could enlighten me what's going wrong, I'd really appreciate it!

(Note, in all the code snippets above, where I quote e.g. Range("A1") this is shorthand. There is in fact a lot more code involved in looping and selecting values, but I know this works, so I am not concerned. The extracts above just demonstrate what happens for the first value in each loop.)

1

1 Answers

2
votes

try

Range("E1").NumberFormat = "mm/dd/yyyy"
Range("E1") = Format(new_array(7, 1), "mm/dd/yyyy")