优秀的文本到时间

我有一个Excel格式的表格,格式如下文所示。 我需要将时间从文本string转换为可用的格式。 我会很高兴,如果我可以在相同的格式IE浏览器的一切都在几秒钟内,并从那里工作。 我知道我可以做一个帮手专栏和一个非常长的丑陋的IF左,右,中等公式和分割一切,但我每天与成千上万的工作,并希望使用dynamic公式或VBscript,使这些更容易工作。

AB 1 Server(A) 15d 3h 39m 2 Server(E) 3h 36m 44s 3 Server(C) 4m 3s 4 Server(B) 44s 

这并不优雅,但只要您的格式如下所述,它就可以作为UDF使用:

 Public Function timeStringToSeconds(strIn As String) As Long Dim values values = Split(strIn, " ") For Each v In values Select Case Right$(v, 1) Case "d" timeStringToSeconds = timeStringToSeconds + CLng(Left$(v, Len(v) - 1)) * 86400 Case "h" timeStringToSeconds = timeStringToSeconds + CLng(Left$(v, Len(v) - 1)) * 3600 Case "m" timeStringToSeconds = timeStringToSeconds + CLng(Left$(v, Len(v) - 1)) * 60 Case "s" timeStringToSeconds = timeStringToSeconds + CLng(Left$(v, Len(v) - 1)) End Select Next End Function 

你可以简单地使用它:在C1例如: timeStringToSeconds(B1)或者通过做这样的事情来运行它: range.value = timeStringToSeconds(range.value)

另一个UGLY的方式来实现你的string到像dd:hh:mm:ss这样的可用格式 。 当然,如果你只需要秒,我们也可以即兴;)

一旦你尝试了,请评论。 我将这种情况称为多分隔符组合 :),我们把d, h, m, s作为分隔符。 也可以使用split函数和正则regexp解决scheme

DD:HH:MM:SS

码:

 Function multiSplitCombine(ByVal strTime As String) As String Dim delimsArray(0 To 3) As Variant Dim i As Long, j As Long, k As Long 'set delimiters delimsArray(0) = "d" delimsArray(1) = "h" delimsArray(2) = "m" delimsArray(3) = "s" If Len(strTime) = 0 Then multiSplitCombine = "00:00:00:00" Exit Function End If For i = LBound(delimsArray) To UBound(delimsArray) '-- get the position of the delimiter j = InStr(1, strTime, delimsArray(i)) '-- if the delimiter is not found If j = 0 Then '-- insert 00: into the position after earlier previous delimiter replacement strTime = Left(strTime, k) & "00:" & Right(strTime, Len(strTime) - k) Else k = j '-- replace delimiter with semicolon strTime = Replace(strTime, delimsArray(i), ":") End If Next i '-- strip that last extra semi colon strTime = Trim(Left(strTime, Len(strTime) - 1)) '-- remove internal white spaces strTime = Replace(strTime, " ", "") '-- back to sheet multiSplitCombine = Application.WorksheetFunction.Text(strTime, "dd:hh:mm:ss") End Function 

很快

在这里你需要改变上面的代码,

  • 将函数名更改为splitToSeconds
  • replacestrTime = Replace(strTime," ", "")后的所有strTime = Replace(strTime," ", "")通过添加以下代码strTime = Replace(strTime," ", "")

     '-- dd:hh:mm:ss format strTime = Application.WorksheetFunction.Text(strTime, "dd:hh:mm:ss") '-- split by semicolon s = Split(strTime, ":") '-- it has to be 4 elements since the format we insert is d:h:m:s splitToSeconds = CDbl(s(0)) * 24 * 60 * 60 + _ CDbl(s(1)) * 60 * 60 + CDbl(s(2)) * 60 + CDbl(s(3)) 

输出:

在这里输入图像描述