问题
I am working on processing of log or history file. In column 1 there is timestamp like this Wed Mar 01 22:08:01 EST 2017. I am copying the entire contents of the sheet into 2d variant array for further processing. Now I want to store this timestamp as date or datetime to further process it.
but if I do
dim dTimeStamp as date
and in the loop use it to store the value of column1 dTimeStamp = cdate(vbaseArray(I,1))
it gives me typemismatch error.
Is there a way I can store timestamp value as date or datetime? Please suggest.
回答1:
You can't convert that string into a date automatically, so you have to parse it. Generally, DateValue is a little more forgiving than CDate.
From the immediate windows
?datevalue(mid("Wed Mar 01 22:08:01 EST 2017",5,15))
3/1/2017
That will always give you the current year. It cuts of the day of week and stops after the time.
If you need the year, or you just want to be more robust, I'd use a function like
Function ConvertDate(ByVal sDate As String) As Date
Dim vaSplit As Variant
vaSplit = Split(sDate, Space(1))
ConvertDate = DateValue(vaSplit(1) & Space(1) & vaSplit(2) & ", " & vaSplit(5)) + TimeValue(vaSplit(3))
End Function
From the immediate window
?convertdate("Wed Mar 01 22:08:01 EST 2017")
3/1/2017 10:08:01 PM
来源:https://stackoverflow.com/questions/42810055/vba-how-to-store-timestamp-in-variable