另一种将字符串转换为可用格式的方法,如 dd:hh:mm:ss。当然,如果您只需要几秒钟,我们也可以即兴发挥;)
试用后请发表评论。我将这种情况称为多分隔符拆分组合:) 我们将d, h, m, s
其视为分隔符。也可以使用split
函数和regexp
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
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))
输出: