Harry Flashman
Active Member
- Joined
- May 1, 2011
- Messages
- 361
I have some code that I wrote ages ago that used to work well but lately it is playing up for some reason and not behaving in a way I would have expected.
I have a value in a cell. It looks like a date but really it is a text string. The value always ends in AM or PM. Here is an example.
06-Jan-2021 08:05AM
I want the value to become a proper Excel date, but without the time (British date formatting, d/mm/yyyy)
6/1/2021
This the routine that I am using.
The problem is because of these two lines of code.
In our example:
06-Jan-2021 08:05AM
The first replace function converts the text value into a date.
6/01/2021 8:05:00 AM
The second line however should not do anything because the text string "PM" does not exist in this particular cell. However something strange has started happening, and this never used to happen. It is switching the day and the month.
1/06/2021 8:05:00 AM
So the date is now 1 June 2021 when it should be 6 of January 2021.
I can rewrite my code to fix this bug, but I am curious as to why it might be happening.
I am using Excel 2013.
If anyone has an idea why this is happening I would be interested to hear your thoughts.
I have a value in a cell. It looks like a date but really it is a text string. The value always ends in AM or PM. Here is an example.
06-Jan-2021 08:05AM
I want the value to become a proper Excel date, but without the time (British date formatting, d/mm/yyyy)
6/1/2021
This the routine that I am using.
VBA Code:
Sub FixDates()
Dim rng As Range, rng2 As Range, rngHRow As Range
Set rng = Range("a1").CurrentRegion
Set rng2 = rng.Offset(1, 0).Resize(rng.Rows.Count - 1).Cells
Set rngHRow = rng.Rows(1).Cells
Dim i As Integer, rngC As Range, rngCell As Range
i = WorksheetFunction.Match("Date", rngHRow, 0)
Set rngDate = rng2.Columns(i).Cells
For Each rngCell In rngDate
rngCell.Value = Replace(rngCell.Value, "AM", " AM")
rngCell.Value = Replace(rngCell.Value, "PM", " PM")
rngCell.Value = WorksheetFunction.RoundDown(rngCell.Value, 0)
rngCell.NumberFormat = "d/mm/yyyy;@"
Next rngCell
End Sub
The problem is because of these two lines of code.
Code:
rngCell.Value = Replace(rngCell.Value, "AM", " AM")
rngCell.Value = Replace(rngCell.Value, "PM", " PM")
In our example:
06-Jan-2021 08:05AM
The first replace function converts the text value into a date.
6/01/2021 8:05:00 AM
The second line however should not do anything because the text string "PM" does not exist in this particular cell. However something strange has started happening, and this never used to happen. It is switching the day and the month.
1/06/2021 8:05:00 AM
So the date is now 1 June 2021 when it should be 6 of January 2021.
I can rewrite my code to fix this bug, but I am curious as to why it might be happening.
I am using Excel 2013.
If anyone has an idea why this is happening I would be interested to hear your thoughts.