VBA how to store timestamp in variable

倾然丶 夕夏残阳落幕 提交于 2019-12-24 10:02:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!