问题是计算机无法知道该字符串日期的格式
12-04-2019 01:03:32 PM AEST
可能是以下两种
dd-mm-yyyy
mm-dd-yyyy
所以你所做的就是让计算机猜测并且它失败了。即使是人类也无法说出这两种格式中的哪一种是正确的。因此,作为字符串且没有实际日期的日期是毫无用处的(除非您有关于格式的其他信息,这不是日期字符串本身的一部分)。
因此,将字符串转换为日期的唯一可行解决方案是,如果您知道这两种格式中的哪一种是正确的,则使用此信息将日期拆分为多个片段并使用DateSerial 函数从中创建一个真实的日期.
您需要对每个单元格执行如下操作作为字符串日期转换。
一个例子
Public Sub ConvertTimeStampToRealDateTime()
Dim TimeStampString As String
TimeStampString = "12-04-2019 01:03:32 PM AEST"
'split by spaces
Dim SplitTimeStamp As Variant
SplitTimeStamp = Split(TimeStampString, " ")
'SplitTimeStamp(0) = "12-04-2019"
'SplitTimeStamp(1) = "01:03:32"
'SplitTimeStamp(2) = "PM"
'SplitTimeStamp(3) = "AEST"
'split date by dash
Dim SplitDate As Variant
SplitDate = Split(SplitTimeStamp(0), "-")
'SplitDate(0) = "12"
'SplitDate(1) = "04"
'SplitDate(2) = "2019"
'now we add the information which of the 3 split parts is day, month and year
'and put it together to a real date
Dim RealDate As Date
RealDate = DateSerial(SplitDate(2), SplitDate(1), SplitDate(0))
'cast time string into a date
Dim RealTime As Date
RealTime = SplitTimeStamp(1) & " " & SplitTimeStamp(2)
'casting from string to date works good for times but not for dates
'so we can do that with the time
'Add date and time to make it a datetime
Dim RealDateTime As Date
RealDateTime = RealDate + RealTime 'note that we need to ADD them mathematically (+) this is not a string concatenation (&)!!!
'AEST: This information about how many hours you need to add or subtract
' from this datetime to convert it into your desired time zone needs
' needs to be done manually
Dim RealDateTimeInMyZone As Date
RealDateTimeInMyZone = DateAdd("h", -3, RealDateTime) 'for example subtract 3 hours
End Sub
最后,您可以将您的真实日期时间写入一个单元格并将Range("A1").NumberFormat
其格式化为您喜欢的格式。
图 1:字符串到日期转换期间的变量值。
请注意,上面的代码只是这个概念的一个例子。如果您需要使其稳固,您可能需要进行一些检查和错误处理,因为它会因意外输入字符串而失败。
此外,用它制作一个可以重复使用的函数可能是一个好主意,例如:
Public Function ConvertDDMMYYYYTimeStampToRealDateTime(ByVal TimeStampString As String) As Date
End Function