Convert String to Excel Date and Time, with specific string format - excel

I've got an Excel/VBA macro which list files in a directory.
Filenames are in format : yyyy-MM-dd#hh-mm-ss_[description].csv
for instance : 2013-07-03#22-43-19_my-file.csv
I then need to get the first part of the filename into an Excel Date object (including a Timestamp)
I found the CDate() function, but it doesn't take any "format" parameter, and the Format() function works the wrong way, ie to convert a String to a Date.
I'd like to get a function with takes a String and a format, and returns an Excel Date/Time object.
Is there a function designed to do that ?
Thanks,

Try this out:
Function ParseDateTime(dt As String) As Date
ParseDateTime = DateValue(Left(dt, 10)) + TimeValue(Replace(Mid(dt, 12, 8), "-", ":"))
End Function

Related

VBA - Parsing Date from Free Form Text String

I am attempting to parse out clean target DATES from cells populated with free form TEXT STRINGS.
ie: TEXT STRING: "ETA: 11/22 (Spring 4.5)" or "ETA 10/30/2019 EOD"
As you can see, there is no clear standard for the position of the date in the string, rendering LEFT or RIGHT formulas futile.
I tried leveraging a VBA function that I found which essentially breaks up the string into parts based on spaces in the string; however it has not been working.
Public Function GetDate(ResNotes As String) As Date
Dim TarDate As Variant
Dim part As Variant
TarDate = Split(ResNotes, " ")
For Each part In ResNotes
If IsDate(part) = True Then
GetDate = part
Exit Function
End If
Next
GetDate = "1/1/2001"
End Function
I'm referring to the cells with text strings as "ResNotes", short for "Resolution Notes" which is the title of the column
"TarDate" refers to the "Target Date" that I am trying to parse out
The result of the custom GETDATE function in Excel gives me a #NAME? error.
I expected the result to give me something along the lines of "10/30/2019"
Unless you need VBA for some other part of your project, this can also be done using worksheet formulas:
=AGGREGATE(15,6,DATEVALUE(MID(SUBSTITUTE(A1," ",REPT(" ",99)),seq_99,99)),1)
where seq_99 is a named formula and refers to:
=IF(ROW($A$1:INDEX($A:$A,255,1))=1,1,(ROW($A$1:INDEX($A:$A,255,1))-1)*99)
*seq_99 generates an array of numbers {1;99;198;297;396;495;...
Format the cell with the formula as a Date of some type.
If there are no dates, it will return an error which you can either leave, or wrap the function in an IFERROR(your_formula,your_error_message)
Algorithm
Split the cell on the spaces
Replace each space with 99 spaces
Using the MID function, return an array of substrings 99 characters long
Apply the DATEVALUE function which will return either an error (if the substring is not a date) or a date serial number.
Since dates in Excel are serial numbers since 1/1/1900, we can use the AGGREGATE function to pick out a value, and ignore errors.
If you are getting #NAME then the code is not stored in a general module. It should NOT be in a worksheet module or ThisWorkbook module.
Also there are few errors in the code. Split returns a String Array. And since IsDate returns TRUE/FALSE the = True is not needed.
As per #MathieuGuindon we can change the string to a date in the code if found and return an error if not. For that we need to allow the return to be a variant.
Public Function GetDate(ResNotes As String)
Dim TarDate() As String
Dim part As Variant
TarDate = Split(ResNotes, " ")
For Each part In TarDate
If IsDate(part) Then
GetDate = CDate(part)
Exit Function
End If
Next
GetDate = "1/1/2001"
'Instead of a hard coded date, one can return an error, just use the next line instead
'GetDate =CVErr(xlErrValue)
End Function
Approach isolating the date string via Filter function
Just for fun another approach demonstrating the use of the Filter function in combination with Split to isolate the date string and split it into date tokens in a second step; finally these tokens are transformed to date using DateSerial:
Function getDat(rng As Range, Optional ByVal tmp = " ") As Variant
If rng.Cells.count > 1 Then Set rng = rng.Cells(1, 1) ' allow only one cell ranges
If Len(rng.value) = 0 Then getDat = vbNullString: Exit Function ' escape empty cells
' [1] analyze cell value; omitted year tokens default to current year
' (valid date strings must include at least one slash, "11/" would be interpreted as Nov 1st)
tmp = Filter(Split(rng.Value2, " "), Match:="/", include:=True) ' isolate Date string
tmp = Split(Join(tmp, "") & "/" & Year(Now), "/") ' split Date tokens
' [2] return date
Const M% = 0, D% = 1, Y& = 2 ' order of date tokens
getDat = VBA.DateSerial(Val(tmp(Y)), Val(tmp(M)), _
IIf(tmp(D) = vbNullString, 1, Val(tmp(D))))
End Function

Excel VBA extract date from CSV txt

I'm having trouble extracting this text, exactly as it appears, from a CSV. There are similar questions posted on SO but they don't match my requirements:
I want to extract "31 January 2017" from this row:
4,'31 January 2017','Funds Received/Credits',56,,401.45,
Currently, VBA considers it "31 Jan" without the year. I've tried applying .NumberFormat to the cell (general, text, date).
SOLUTION REQUIREMENTS:
No user action required -- Interact with the file only using VBA (not using File > Import > Wizard)
Compatible with VBA Excel 2003
Extract the full text regardless of Excel or operating system date settings
Thank you for your ideas
You can use the split function, using the comma as a delimiter like this:
sResult = Split("4,'31 January 2017','Funds Received/Credits',56,,401.45, ", ",")(1)
If you dont want the single quotes, then add the replace function like this:
sResult = Replace(Split("4,'31 January 2017','Funds Received/Credits',56,,401.45, ", ",")(1), "'", "")
If you include the "Microsoft VBScript Regular Expressions 5.5" Reference, you can set up a pattern that will extract the whole date if it is found. For example:
Dim tstring As String
Dim myregexp As RegExp
Dim StrMatch As Object
tstring = 'Line from the CSV, or entire CSV as one string
Set myregexp = New RegExp
myregexp.Pattern = "\d{1,2} [A-Z]{3,9} \d{4}"
Set StrMatch = myregexp.Execute(tstring)
You get the benefit from this method that all the dates in the CSV will be pulled out at once, much faster than using a split line by line. Additionally, the dates may be accessed by using
DateStr = StrMatch.Item(index)
for the whole string line, or substrings can be set up to get specific parts of the string(Such as month, day, year).
myregexp.Pattern = "\(d{1,2}) ([A-Z]{3,9}) (\d{4})"
Set StrMatch = myregexp.Execute(tstring)
DateStr = StrMatch.Item(index1).SubMatches(index2)
It is a very powerful tool, with a simple set of symbols for development of patterns. I highly suggest you familiarize yourself with it for manipulation of large strings.

Excel-VBA "type mismatch" error when using Format() to convert Date to String

I am working on code that runs within a userform in Excel 2013. It is supposed to convert dates to string values to pass into text boxes within the form.
I have done this before and have never had any trouble with it. I am now getting a Runtime Error 13 "type mismatch" whenever I attempt to execute the following code:
Me.ListingDate.Value = Format(Now(), "mm/dd/yyyy")
The objective of this line is to format today's date and pass it to the textbox. I tried breaking it down into individual steps:
Dim MyDate As Date
Dim MyString As String
MyDate = Now()
MyString = Format(MyDate, "mm/dd/yy")
Me.ListingDate.Value = MyString
This still triggers a type mismatch error in the line where the Format() function is invoked on a date value.
I have run this code for over a year and never had any problems. There are several other forms in the file that use a similar syntax and it works.
Is it possible for a userform to become corrupted and falsely generate a runtime error? What other factors may be causing the error?

Format a date into mm.dd.yyyy format

I have a VBA script in which I am trying to convert the string in "yyyymmdd" format to "mm/dd/yyyy" format. However, when I incorporate format function to achieve this, it's showing
"Run time error-6": Overflow
Can any one help me with this ? The following is the correspondig VBA code.
// NewDate is in the format "yyyymmdd" being extracted out of a file path like "C:\Files\20140611\file.csv"
Required_format=Format(NewDate,"mm/dd/yyyy") // This line shows the error
you will have to format this yourself, because Format doesn't know that it is dealing with a date, it simply sees a string.
Use something like (psuedo code):
y = left(NewDate, 4)
m = mid(NewDate, 5, 2)
d = right(NewDate, 2)
Required_format = m + "/" + d + "/" + y
Just be absolutely sure the format is consitant. Any change (especially the padding is notorious) messes up your format.
Here is one more solution:
CDate(format(NewDate,"mm dd yyyy"))
Here's another method. As you wrote above, NewDate contains an 8 digit string representing a date in yyyymmdd format. The following "one liner" will output a date (as a string) in your desired format:
Format(Format(NewDate, "####/##/##"), "mm/dd/yyyy")

Getting type mismatch error in replace function in vba

My vba code is to replace current time and date to 4_17_2014 8_09_00 PM format
But i am getting type mismatch error while running below VBA code
Function Current_Date_Time_Stamp()
Dim CurrTime As Date
CurrTime = Now
MsgBox Now
CurrTime = Replace(CurrTime, "-", "_")
MsgBox CurrTime
CurrTime = Replace(CurrTime, ":", "_")
Current_Date_Time_Stamp = CurrTime
End Function
Can anybody help me why i am getting error
As #Tim Williams mentioned in comments, Replace works only with string variables, but CurrTime is date (actually, date variables doesn't store format of date, but only date itself. Format when displaying date depends on regional settings and number format of your cell).
However you can use function with single line of code like this:
Function Current_Date_Time_Stamp()
Current_Date_Time_Stamp = Format(Now, "mm_dd_yyyy h_mm_ss AM/PM;#")
End Function

Resources