How do I convert Excel General Text to Date - excel

So my problem is I have a Date that is defined as General in Excel as this "10 JUL 2021 10:30" I want to make it Excel Date.
kindly have a look at my picture for detailed understanding.
Need any kind of solution to automate this VBA or any formula,
Thanks in advance

If you need VBA to extract Date, please use the next function:
Function TextToDateX(txt As String) As Date
Dim arrD, arrM
arrM = Split("JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC", ",")
arrD = Split(txt, " ")
TextToDateX = DateSerial(CLng(arrD(2)), Application.match(arrD(1), arrM, 0), CLng(arrD(0))) + CVDate(arrD(3))
End Function
It can be tested as:
Sub testTextToDateX()
Dim txt As String, d As Date
txt = "10 JUL 2021 10:30"
d = TextToDateX(txt)
Debug.Print Format(d, "dd/mm/yyyy hh:mm")
End Sub
DateValue is localization related. Microsoft states: "DateValue recognizes the order for month, day, and year according to the Short Date format that you specified for your system". So, it may work or not.
In my case it doesn't...

I just tried using the DateValue() worksheet function, and every worked fine (normal Excel formula, no VBA needed):
=DATEVALUE("07 JUL 2021 10:30")
One thing that might be interesting for you: there exists a cell formatting (dd mmm yyyy hh:mm), which you seem to be using. (When you apply this on any cell, the value inside gets automatically formatted into that kind of date format.)
Edit, based on comment:
In case there's a comma in your date string, remove it first and then apply the DateValue() function:
=DATEVALUE(SUBSTITUTE("07 JUL 2021, 10:30",",",""))

Related

VBA Date + TimeValue returns no time

I have a date and time which I assemble into a date + time from strings in the form
date_string = "2020-12-30" 'yyyy-mm-dd
date_code = CDate(date_string)
time_string = "00:00:00" 'hh:mm:ss
time_code = TimeValue(time_string)
date_time = date_code + time_code
Commonly the return looks like 05.01.2019 11:00:00, which is what I expect.
The returned values also all check out as TRUE if I test with IsDate(date_time)
Whenever the time is 00:00:00 however, I only get the date returned with no time appended. I dont quite understand this, since TimeValue(time_string)returns 00:00:00.
So it must be an issue when combining date and time to a date + time string.
Can someone please enlighten me why midnight somehow does no exist in Excel VBA or where my error in creating the time code is?
EDIT:
I try to explain my situation a bit better:
I do this date date/time stuff in code and then but the result in an array in a loop. Only later on it is written to a cell in a table.
By the time is is written into a cell, even custom formatting the cell to "DD.MM.YYYY hh:mm" does not show the time as it is completely missing from the cell value.
Do I neet to apply a format at the point of date_code + time_code?
Sometimes the answer can be so simple. Thanks to Variatus and Paul I checked formatting out.
I applied a date_time = Format(date_code + time_code, "dd.mm.yyyy hh:mm") in my code. Using this, my code runs as expected and 00:00:00 appears as expected, even in the cell values of the Excel table.
When you enter an integer, like 43930, in a cell Excel will record the number as an integer, just as you entered it. You can then proceed to format the cell as #,##0.000 and thereby make the number display as 43930.000. Or you can format that very same number as custom dd mmm yyy hh:mm:ss and display it as 09 Apr 2020 00:00:00. The point is that Excel chose to record the number in its most efficient way, as an integer.
So, if you enter a DateValue + TimeValue which, together, amount to an integer Excel will record the integer correctly. The format in which that integer is displayed in your worksheet is a matter for cell formatting.

Determining if a date falls between a certain range

I'm trying to extract a date from a spreadsheet that falls between 01/07/2019 and 31/07/2019 and save that in the variable chantalJulyTotalDemanded.
Dim julyStart As Date
Dim julyFinish As Date
julyStart = CDate("01/07/2019")
julyFinish = CDate("31/07/2019")
If CDate(dataSheet.Cells(x, 12)) >= CDate(julyStart) And _
CDate(dataSheet.Cells(x, 12)) <= CDate(JulyFinish) Then
chantalJulyTotalDemanded = chantalJulyTotalDemanded + dataSheet.Cells(x, 10)
The above also grabs information from dates in August.
The date from the spreadsheet is in the format 1/07/2019.
Less of an answer and more of suggestions:
For date constants in VBA code, use #
julyStart = #1/7/2019#
I'm not sure sure about how VBA determines if this is Jan 7 or Jul 1. But what I suggest you do is break in VBA and move mouse over vars to see what it shows you.
In your loop create a variable for the cell value:
Dim cellDate As Date: cellDate = dataSheet.Cells(x, 12)
Now in break mode, you can inspect the variables to see if they are as you expect.
No need to run CDate on CDate(julyStart) since julyStart is already a date.
I'm assuming your date value in the cell is an actual date number value. If so, you shouldn't have any problem. But if it's a string value, then you'll need to figure out if CDate is performing the proper conversion of say 1/7/2019 vs 7/1/2019.

My function always reads date wrong by exactly 1 year

I have dates stored in strings, sometimes in the form of "Nov-2018" and sometimes in the form of "11/1/2018". I want to change them universally to "Nov 2018". Just month and date.
I wrote the following function.
Function FnDateExtract(fnFile, fnTab, fnRow, fnColumn)
Dim RawExtract As String
With Workbooks(fnFile).Worksheets(fnTab)
RawExtract = .Cells(fnRow, fnColumn).Text
FnDateExtract = Format(RawExtract, "mmm yyyy")
End With
End Function
I keep getting into this problem where the function would read strings '11/1/2018' and 'Nov-2018' and return the result 'Nov 2019'. I have no clue why 2019 (but the problem only appeared from January 1, 2019 onward. How strange.)
Question:
As a temporary solution, is there a way to return the year minus 1? Something akin to FnDateExtract = Format(RawExtract, "mmm yyyy - 1")?
If you could help me solve the problem why the function always misreads strings by exactly 1 year, that'd also help a lot. Thanks!
Edit
RonRosenfeld below suggested that the function would only extract the current year. I did a few tests and it seems like it would also extract 2017 as 2019. Not sure why that is. Still looking for a solution.
Use the IsDate check combined with the CDate conversion to achieve the correct string representing a date.
Option Explicit
Function FnDateExtract(fnFile As String, fnTab As String, fnRow As Long, fnColumn As Variant)
With Workbooks(fnFile).Worksheets(fnTab)
If IsDate(.Cells(fnRow, fnColumn).Text) Then
FnDateExtract = Format(CDate(.Cells(fnRow, fnColumn).Text), "mmm yyyy")
End If
End With
End Function

Converting date and time text to date and time format in Excel

Is there any way to format the following text to date and time format in Excel? Nothing I try works.
Fri, November 16 2018 8:00 PM
I have tried doing the following, with no luck.
=TEXT("Fri, November 16 2018 8:00 PM","ddd, mmm d yyyy h:mm AM/PM")
If you want to avoid VBA, then you need to use the DATEVALUE and TIMEVALUE functions. Unfortunately these functions aren't smart enough to convert the text you describe, but you can still split up the text with cell formula prior to inputting into these functions.
The following formula will convert the text Fri, November 16 2018 8:00 PM to a date/time value (assuming text is in cell A1).
=DATEVALUE(SUBSTITUTE(MID(A1, FIND(" ",A1)+1, FIND("|", SUBSTITUTE(A1," ","|",4))-FIND(" ",A1)), " ", ", ", 2)) + TIMEVALUE(RIGHT(A1, LEN(A1)-FIND("|", SUBSTITUTE(A1," ","|",4))))
You can create your own custom UDF and use it like a worksheet function:
Public Function myDateToDate(inputRng As Range) As Date
With CreateObject("VBScript.RegExp")
.Pattern = "\w{3},\s(\w+\s\d+\s\d+)\s(\d+:\d+\s\w+)"
If .test(inputRng.Value) Then
With .Execute(inputRng.Value)(0).SubMatches
myDateToDate = CDate(.Item(0)) + CDate(.Item(1))
End With
End If
End With
End Function
This will use Regular Expressions (RegEx) to grab the values in your string, and capture both the date and the time. Since within Excel all a date is is a number, you can add the first capturing group (\w+\s\d+\s\d+) (which represents the date) with the second capturing group (\d+:\d+\s\w+) (which represents the time) together. (See how the regex pattern works here).
After you have done this, you can now use your newly-created UDF by using the worksheet formula =myDateToDate(A1) - where A1 would be replaced with the cell/string that contains your date.
If you are unfamiliar with VBA, read on:
How do I access the VBE?
You can gain access to VBE by pressing Alt + F11 while you are inside your workbook.
Okay, So I have the VBE open. Now how do I apply this Sub/UDF?
In the left pane you will see your workbook object modules. This is called the Project Explorer. You will need to create a new module, which you can do by right-clicking inside the Project Explorer > Insert > Module:
Now you can paste the Sub/UDF to this new module and you are all set!
A monstrosity but should be locale independent (either US or UK):
=DATE(LEFT(RIGHT(A1,13),5),MONTH(DATEVALUE(LEFT(MID(A1,6,9),FIND(" ",MID(A1,6,10)))&"1")),MID(MID(A1,FIND(" ",A1)+1,99),FIND(" ",MID(A1,FIND(" ",A1)+1,99))+1,2))+LEFT(TRIM(RIGHT(A1,8)),7)
Nice regex solution above, you can also do it in a different way:
Function ConvertToDate(str As String) As Date
Dim arr() As String
arr = Split(str, " ")
ConvertToDate = CDate(arr(3) & "/" & Month("01/" & arr(1) & "/2018") & "/" & arr(2) & " " & arr(4))
End Function

Why does transposing array with dates in format dd/mm/yy change some dates to mm/dd/yy format?

Behavior:
When I transpose a 1 dimensional array, containing dates, in order to print them to a sheet in it's entirety, some dates are changed from the dd/mm/yy to mm/dd/yyyy.
In particular, when the day of the month:
is less than or equal to 12, such as January 2, 2016 (02/01/16), or May 11, 2016 (11/05/16), then the date is printed with the date format mm/dd/yy and is aligned right.
is greater than or equal to 13, such as April 23, 2016 (23/04/16), or December 17, 2016 (17/12/16), then the date is printed with the date format dd/mm/yyyy and is aligned left.
When I use a for loop to print each date separately, or I do not transpose the array and print each date in the first row of each column however, all dates are printed with the format dd/mm/yy and all dates are aligned right.
Additional information:
I have:
Windows 8.1 (English U.S.)
Office 365 Student (English U.S) (Excel 2016 32 bit)
Locale setting: Netherlands
Code:
Option Explicit
Sub TransposeDatesArray()
Dim arrDates() As Date
Dim i As Variant
ReDim arrDates(0)
For i = CDate("Januari 01, 2016") To CDate("December 31, 2016")
If UBound(arrDates) = 0 Then
ReDim arrDates(1 To 1)
Else
ReDim Preserve arrDates(1 To UBound(arrDates) + 1)
End If
arrDates(UBound(arrDates)) = i
Next
With ThisWorkbook.Worksheets(1)
.Cells.Delete
.Cells(1, 1).Resize(UBound(arrDates)).Value = Application.Transpose(arrDates)
.Cells(1, 2).Resize(UBound(arrDates)).Value2 = Application.Transpose(arrDates)
.Cells(1, 3).Resize(UBound(arrDates)).Formula = Application.Transpose(arrDates)
For i = LBound(arrDates) To UBound(arrDates)
.Cells(i, 4).Value = arrDates(i)
.Cells(i, 5).Value2 = arrDates(i)
.Cells(i, 6).Formula = arrDates(i)
Next
End With
End Sub
Result:
After doing some more research, I have found the following:
It would seem that the Application.Transpose(arrDate) transposes not only the array, but also date values when they are stored as actual date.
Consider the date , 42373 (January 4, 2016)
Debug.Print Format(CDate(42373), "mmmm d, yyyy")
produces januari 4, 2016
Debug.Print Application.Transpose(Format(CDate(42373), "mmmm d, yyyy"))
produces april 1, 2016
It appears that a date value can be transposed when stored as an actual date. The transposing effectively reorders the date from day/month to month/day after which the the month becomes the day and the day becomes the month because the system still uses the day/month format. This can only be done if the day of the month is 12 or less, because after transposing the day becomes the month.
I hit this problem, but interestingly, the date switch (from dd/mm to mm/dd) on transpose only happened when I ran the macro from a toolbar button; if I ran it from inside the VBA editor, or from the Developer menu>Macros dialogue box, it worked fine.
To make it work no matter where I ran the macro from, I added a function before the transpose to convert all dates to strings (looping through my array and using the CStr function), and then converted back from strings to dates after the transpose (another loop and CDate function) - the loops having to be slightly different to account for the transposed dimensions.
Transposing array with Application.Transpose() transforms the "Date" data type into "String". Not able to explain why.
So my suggestion is to transform the Column with "Date" data type into "Long" before you do the Application.Transpose() (simply using CLng).
After that you can either transform it back to "Date" or just set the number format as "Date" for the cells, where you would like to paste the array.
I resolve this issue using .FormulaLocal to write back the array in the sheet.

Resources