如何将文本转换为date和由vba总结时间?

你好吗? 看,我打开一个制表符分隔的文件,其中包含关于分析样本的date和时间的信息。 我想总结一下时间和date,以便根据这些信息对行进行sorting。

时间和date以stringforms存储在两个不同的单元格中,如下所示:date:29/11/2013 13:41:59:546

因此,我必须创build一个公式来删除“date:”,并将“:546”转换为毫秒,并添加到其余的数字。 不幸的是,即使删除了“Date:”,考虑到date被excel解释为一个数字,我不能将“29/11/2013”​​转换为一个数字。 这很有趣,因为在打开工作簿的情况下,如果select29/11/2013(在“Date:”被删除之后)的单元格并按F2,则input,excel将其转换为数字。 当我试图通过VBA做同样的事情时,我错过了什么?

我的结果应该是一个适当格式的数字

.numberformat="dd/mm/yyyy hh:mm:ss.000" 

应该显示29/11/2013 13:41:59.546。

我的function是:

 Function DateTimeCustomFormat(TimeCell As Range, DateCell As Range, formatTime As String, formatDate As String) Dim ms As Double 'Means milliseconds Dim msTOday As Long 'Factor to convert ms to day (ms divided by all milliseconds in a day) msTOday = 86400000 Select Case formatTime Case "hh:mm:ss:ms(xxx)" ms = Val(Right(TimeCell, 3)) / msTOday TimeCell = Left(TimeCell, Len(TimeCell) - 4) TimeCell.NumberFormat = "0.00" '"h:mm:ss.000" TimeCell = TimeCell + ms End Select Select Case formatDate Case "Date: dd/mm/yyyy" DateCell = Right(DateCell, Len(DateCell) - 6) DateCell.NumberFormat = "dd:mm:aaaa" 'DateCell = DateCell.Value * 1 End Select DateTimeCustomFormat = TimeCell + DateCell End Function 

看起来好像你不太熟悉像Range这样的对象数据types,以及用户定义的函数可以做什么以及不能做什么。

在你的代码中,你得到参数TimeCell作为Range,但是你用一个string( TimeCell = Left(TimeCell, Len(TimeCell) - 4) )覆盖了这个,然后你尝试设置NumberFormat。 一个string没有NumberFormat ;-)。 此外,用户定义的函数不能将NumberFormat设置为单元格,并且如果这是上述代码行的目标,它也不能设置单元格值。 它只能返回一个值。 这个值就是单元格的值,它包含用户定义的函数作为公式。

与DateCell相同的问题。

你的代码应该得到表示时间或date的单元格值的部分作为string,然后将它们转换为date。 因此一些function是可用的。

易于使用的是TimeValue和DateValue。 但是这些function取决于date和时间格式的系统设置。 所以可能是他们没有得到正确的价值观。 例如“06/07/2014”的date如果是7月06日或07年6月,则不太清楚。这取决于系统date格式设置。

更一般的解决scheme是使用TimeSerial和DateSerial。 在我看来,这是更好的解决scheme,因为他们的准确定义。

 Function DateTimeCustomFormat(TimeCell As Range, DateCell As Range, formatTime As String, formatDate As String) As Date Dim ms As Double 'Means milliseconds Dim msTOday As Long 'Factor to convert ms to day (ms divided by all milliseconds in a day) Dim sTime As String, sDate As String 'String parts of the given parameters Dim dTime As Date, dDate As Date 'Calculated datetime values of the given parameters msTOday = 86400000 Select Case formatTime Case "hh:mm:ss:ms(xxx)" ms = Val(Right(TimeCell.Value, 3)) / msTOday sTime = Left(TimeCell.Value, Len(TimeCell.Value) - 4) 'dTime = TimeValue(sTime) + ms 'please read help for TimeValue dTime = TimeSerial(Left(sTime, 2), Mid(sTime, 4, 2), Mid(sTime, 7, 2)) + ms Case Else dTime = 0 End Select Select Case formatDate Case "Date: dd/mm/yyyy" sDate = Right(DateCell.Value, Len(DateCell.Value) - 6) 'dDate = DateValue(sDate) 'please read help for DateValue dDate = DateSerial(Right(sDate, 4), Mid(sDate, 4, 2), Left(sDate, 2)) Case Else dDate = 0 End Select DateTimeCustomFormat = dTime + dDate End Function 

用作UDF(用户定义的函数): 在这里输入图像描述