Cannot convert date string to datevalue in Excel - excel

I have some dates in a string in a column.
Because the format seems to be M/DD/YYYY I sometimes get a VALUE error when using DATEVALUE.
How can I convert a column to make sure all dates are correct.
For example, the following 2 cells
9/29/2006 12:49:58.956 AM DATEVALUE gives an error
9/12/2008 5:36:59.356 PM DATEVALUE converts to 39791

You need to select the range (just one colunm) with the dates... Go to:
(in Excel 2010)
Data >>> Text to Columns
Inside the dialog box select:
Delimited >>> Next
Just select Tab checkbox.
And heres is the magic!
You need to define the arrangement for your dates...
In the Date field:
Choose the what you need (as you say in your question is M/D/Y)
Destination field:
Make sure that is the same of the data you want to format.
And finish.

The problem you are having is probably that the data is getting interpreted as a general field, and shows up as, say 49:59.0 - which isn't text, which is what Datevalue() expects as input; for both inputs, Datevalue(CellID) words if you prepend the text with a ' - which ensures it is treated as text.

it seems that your system settings use dd/mm/yyyy for short date format. and datevalue function uses this settings, so its try to read the day from the first part of the string and the month from the second part. as in your example 9/29/2006 12:49:58.956 AM there is no month with 29 then it gives error, and in the second example it gives 39791 = 9 december 2008 and NOT 12 september 2008.
If you change the short date format in your system settings to mm/dd/yyyythen datevalue function will work correctly, but this not acceptable, so we need to replace month with day and day with month to get correct date.
I don't know if we can do this with Excel formula but we can do that simply with VBA.
So try this code:
Sub Test()
Dim d1 As Variant, d2 As Variant, td As Date
Dim Rng As Range, CL As Range
Set Rng = Range("A1:A2") ' change this to your range
For Each CL In Rng
d1 = Split(CL.Value, " ")
d2 = Split(d1(0), "/")
td = DateSerial(d2(2), d2(0), d2(1))
CL.Offset(0, 1) = td
CL.Offset(0, 1).NumberFormat = "mm/dd/yyyy" ' change the Date format as you need
'CL.Offset(0, 1).NumberFormat = "dd/mm/yyyy"
Next
End Sub

Related

Problem with value as date and format as text in cell

I'm writing a Macro where I need two things in one of the column ranges:
a) Cell values must be the date of the next day in the dd/mm/yyyy format;
b) Cell Format must be text
I keep running into the problem of the date format being changed to mm/dd/yyyy.
Default excel format for the vba function date is dd/mm/yyyy ,since my excel language is set to Portuguese.
By running:
Sub format()
Range("A1").Value = Date + 1
End Sub
I get the value 11/02/2023, date format, which is expected. But if I run:
Sub format2()
Range("A1").NumberFormat = "#"
Range("A1").Value = Date + 1
End Sub
The output is 02/11/2023 in text, in the mm/dd/yyyy format. I'd like to understand why this would even happen
Same thing happens for me. Not sure why but you can achieve what you want by doing:
Sub format2()
Range("A1").NumberFormat = "#"
Range("A1").Value = format(Date + 1, "dd\/mm\/yyyy")
End Sub
This will result in the cell being formatted as text in format "dd/mm/yyyy".
If you wanted the same format but actually formatted as date, you should do this:
Sub format2()
Range("A1").NumberFormat = "dd\/mm\/yyyy;#"
Range("A1").Value = Date + 1
End Sub
The backslashes are there because excel (at least on my system) considers the forward slash a substitute for default separator and replaces it with hyphens, which are my actual default separators.
I'd like to credit this answer for the last point (escaping the forward slashes): https://stackoverflow.com/a/8527762/9852011

I need to change format of a date column from D-M-Y to Y-M-D in excel

I was trying to import a CSV file to my phpmyadmin. Then my date field had values as 0000-00-00 since both date formats were different. I changed the CSV date-format to the format in the database. I have 5000+ data in my CSV. but only a few dates change to the format I chose. Remaining still in the old format
I went to Format cells, selected date, changed to Uk and selected the desired date format. But only a few dates change to the format I chose. Remaining still in the old format
Starting with data like:
Select the cells you wish to convert and run this:
Sub FixDate()
Dim s As String, d As String, rng As Range, cell As Range
Dim dt As Date
d = "-"
For Each cell In Selection
s = cell.Text
If InStr(s, d) > 0 Then
arr = Split(s, d)
dt = DateSerial(arr(2), arr(1), arr(0))
cell.Clear
cell.Value = dt
cell.NumberFormat = "dd-mm-yyy"
End If
Next cell
End Sub
to produce:
You can only change the date format in Excel once Excel recognizes the cell contents as dates. If this doesn't happen automatically, you can force it with the Text to columns function. After the dates have been recognized, you can use any date format you like.
Select the column with the unrecognised dates, and go to Data tab, click Text to columns.
Select Delimited, Next, Untick everything, Next, Select Date and from the dropdown select the order in which the dates currently are in your column. Hit Finish.
In my example dates are in yyyy-dd-mm format.
This is the fastest way I know of in Excel to make it recognize dates in any order.

How to separate date-time stamp into 2 columns?

I have a spreadsheet with a column containing two different datetime formats that I'm trying to split into a standardised column. The two formats are as such:
21/09/2017 7:39
14/07/17 13:47
I've tried splitting out the datetime components individually, but it appears the YEAR function doesn't like parsing the two digit dates. As a ghetto workaround, I've done a find and replace, but this isn't sustainable. Any excel geniuses out there have any ideas or functions I should be looking at?
Cheers
Since you wanted a VBA response to your question, here it is.
You will need to make adjustments to your range, as this is only going to pull off of A1 (you didn't specify the original range with the text dates, nor the ranges of the new date and times).
Option Explicit
Sub SplitDateAndTime()
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets(1)
Dim RawVal As String, RawDate As String, RawTime As String
RawVal = ws.Range("A1").Value
RawDate = Split(RawVal, " ")(0)
RawTime = Split(RawVal, " ")(1)
Dim NewDate As Date, NewTime As Date
NewDate = CDate(RawDate)
NewTime = CDate(RawTime)
ws.Range("A1") = NewDate
ws.Range("B1") = NewTime
End Sub
Please note this formula assumes all of your dates will be after the year 2000. If that's not true, let me know and I'll figure something else out.
It looks like your first date is being recognised as a proper datetime, while your second is a text value.
Here is what I've worked out:
There is an =IFERROR formula in both the Date and Time columns. The first formula in each works on the datetime format, and the second works on the text format and can be dragged down to work on any cell reference.
This is the formula in B1:
=IFERROR(DATE(TEXT(A2,"yyyy"),TEXT(A2,"mm"),TEXT(A2,"dd")), DATE(MID(MID(A2,FIND("/",A2)+1,5),FIND("/",MID(A2,FIND("/",A2)+1,5))+1,2)+2000,MID(A2,FIND("/",A2)+1,2),LEFT(A2,FIND("/",A2)-1)))
And this is the formula in C1:
=IFERROR(TIME(TEXT(A2,"hh"),TEXT(A2,"mm"),0),TIME(LEFT(MID(A2,FIND(":",A2)-2,5),FIND(":",MID(A2,FIND(":",A2)-2,5))-1),MID(MID(A2,FIND(":",A2)-2,5),FIND(":",MID(A2,FIND(":",A2)-2,5))+1,256),0))
To get the Date assuming that your data in on column A
=DATEVALUE(MID(A1,1,FIND(" ",A1)-1))
T0 get the Time assuming that your data in on column A
=TIMEVALUE(MID(A1,FIND(" ",A1)+1,5))

Copy/paste dates exactly as displayed? Not necessarily the format, but as they're displayed visually

I can't seem to figure out how to overwrite my date with what's being displayed.
For example, what's being displayed is 06/01/2016, but the actual data behind that is showing 01/06/2016. The date I want to have in there is June 1, 2016 (which is what's displayed). Changing the format of the cell doesn't help, because I'm doing some formulas with the Dates later, so actually need to have Excel have the correct date.
I have about 10,000 of such dates, where the displayed date is exactly what I want to have, but the actual formula "reversed".
Essentially, I would love to just copy that column (or run a sub) that puts what the cell literally displays into the cell.
What sort of works is doing this, but it only works on those cells with "backwards" dates...essentially passing the day as a month, and month as a day.
=DATE(YEAR(C1),DAY(C1),MONTH(C1)).
It "falls apart" though when the date is actually correct and I don't want it to change:
So, what'd be best is to just literally overwrite the cell with what's displayed.
Or, what would an IF statement be that I could use to somehow check if the date displayed is what I want, and if so keep that, otherwise use that =DATE(YEAR(),DAY(),MONTH()) "trick"?
I also tried =IF(DAY(C2)>12,DATE(YEAR(C2),DAY(C2),MONTH(C2)),C2) but that doesn't work either because it returns June 01 2016 for both 01/06/2016 and 06/01/2016.
I may be overlooking something simple, I've been staring at this for an hour or so...Any thoughts/ideas are appreciated!
Say wee have dates in column C from C1 through C100 that appear to be correct. (so if you see 06/12/2017 you want it to be June 12th and not December 6th)
Try this short macro:
Sub dateFixer()
Dim ary(1 To 100) As String
Dim rng As Range, r As Range
Dim i As Long
Set rng = Range("C1:C100")
i = 1
For Each r In rng
ary(i) = r.Text
i = i + 1
Next r
rng.Clear
rng.NumberFormat = "mm/dd/yyyy"
i = 1
For Each r In rng
r.Value = ary(i)
i = i + 1
Next r
End Sub
A really clean solution is to use the CELL() function.
=CELL("format",A1) will return "D1" for cells formatted as d/m/y, and "D4" for cells formatted m/d/y. So, with this you can conditionally flip month and day:
=IF(CELL("format",A2)="D1",DATE(YEAR(A2),DAY(A2),MONTH(A2)),A2)
The Text property of a range returns the display text: "what the cell literally displays."
Note that literal is the right word - for example, if your column is too narrow, Text will return the displayed ##### characters instead of any useful value.
The Text property will not return an array, so you'll have to loop through your range and read/write individual cells with something like this:
For Each c in rng
c.Value = c.Text
Next c
Incidentally, the documentation on this property is almost nonexistent. This blog post goes into a more detailed review of the property and how it relates to Value and Value2.

How can I keep the date format from a VLookup returned value?

I have a sheet whit mixed format data (dates, double, strings, etc.).
I search the value (my_index) in the lookup_range and I want to retrieve the data to change with it a cell in other sheet. It works fine, but when the value returned by VLookup is a date and I set it to the other sheet it looses its date format.
Dim lookup_range As Range
Dim my_index, my_value As Variant
my_value = Application.VLookup(my_index, lookup_range, num_col, False)
Sheets(3).Cells(num_row, last_col_s1 + num_col - 1).Value = my_value
So, when the data in the lookup_range is 02/05/2014 the data showed at sheet-3 looks like 41761.
I need to keep the original data format of the data in the lookup_range.
VLOOKUP doesn't care about the formatting of the data it's returning - it returns data, not formats.
The only way to ensure the same format as the source, is to copy/paste that format, either manually or programmatically.
use this
Sheets(3).Cells(num_row, last_col_s1 + num_col - 1).Value = cdate(my_value)
I had the same problem, and simply reformatted the VLOOKUP cell to also be in date-time format. That fixed my issue. I am not sure how date-time gets translated into a number, but it does.
i faced the same issue. After vlookup, change the format to "ShortDate" format. This will give you what you are looking for.
Excel Formula :
=TEXT(VLOOKUP(Lookup_value,table_array,col_index_num,0),"dd-mm-yyyy")
VBA :
Sub vlookup_code()
Dim table_rng As Range
'FOR THE TIME BEING GIVING A LOOKUP VALUE
look_up_value = "sekar"
'SETTING THE TABLE ARRAY RANGE
Set table_rng = Sheet1.Range("C3").CurrentRegion
'SINCE VLOOKUP WILL GIVE AN ERROR, IF THE LOOKUP VALUE IS NOT PRESENT
'TO HANDLE THIS ERROR, WE USE THE ISERROR STATEMENT
If IsError(Application.vlookup(look_up_value, table_rng, 2, 0)) = False Then
vlook_value = WorksheetFunction.vlookup(look_up_value, table_rng, 2, False)
'CHANGING THE VLOOKUP VALUE FORMAT TO DATE FORMAT
date_format = WorksheetFunction.Text(vlook_value, "dd-mm-yyyy")
End If
End Sub
In Microsoft Office 2016.
Once data copied to the cell. Select the column which needs to be in date format. Right click->format cells, go to Number tab and select date from the drop-down and choose the required date format, data will be converted to date format.

Resources