将包含天,小时和分钟的字符串转换为hh:mm:ss

时间:2012-02-17 10:15:34

标签: string excel time

我要处理400条记录,它们采用以下格式(字符串):

3h
24h20min
3h
2d
26min
1h12min
17h35min
6h12min
30s

如何制作一个自动检测dhmins的公式,然后将其转换为右hh:mm:ss最终高于24?

3 个答案:

答案 0 :(得分:2)

这个previous answer of mine会让你成为一部分。

稍作调整:

=VALUE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(B5,"d"," "),"h",":"),
 "min",":"),"s",""))

然后将单元格格式化为[h]:mm:ss,其中[h]表示允许大于24的小时数(而不是环绕为零)。

我并不是说这个公式适用于所有情况。事实上,当你有单独的分钟,单独的秒数,几天和几分钟但没有时间等等时,它会失败。但是,你要求“帮助或线索”,这确实应该为你设计一个合适的公式起点适合您的情况。

enter image description here

编辑 Arrrrrhhhh,我无法抗拒。我创建了一个VBA用户定义函数来解析日期字符串。它非常强大,适用于所有示例和更多 - 甚至包含随机字符的字符串,例如6d 243min + 7s。请注意,您仍然需要将单元格格式设置为[h]:mm:ss

enter image description here

Function ParseDateTime(sTime As String) As Date

    Dim i As Long
    Dim identifierPos As Long
    Dim iTimeUnit As Long
    Dim nTimeUnit As Long
    Dim timeUnitCount As Long
    Dim timeUnitIdentifier() As String
    Dim timeUnitDateValue() As Date
    Dim thisDate As Date

    ' What are we looking for in the string?
    ReDim timeUnitIdentifier(1 To 4)
    timeUnitIdentifier(1) = "d"
    timeUnitIdentifier(2) = "h"
    timeUnitIdentifier(3) = "min"
    timeUnitIdentifier(4) = "s"

    ' What does each of these identifiers mean?
    ReDim timeUnitDateValue(1 To 4)
    timeUnitDateValue(1) = 1 ' value of 1 means 1 day in Date type.
    timeUnitDateValue(2) = TimeSerial(1, 0, 0)
    timeUnitDateValue(3) = TimeSerial(0, 1, 0)
    timeUnitDateValue(4) = TimeSerial(0, 0, 1)

    nTimeUnit = UBound(timeUnitIdentifier)

    ' Treat each time unit separately
    For iTimeUnit = 1 To nTimeUnit
        ' Try to locate this time unit's identifier
        identifierPos = InStr(sTime, timeUnitIdentifier(iTimeUnit))
        If identifierPos > 0 Then
            ' Found it. Extract the digits that precede the identifier.
            For i = identifierPos - 1 To 1 Step -1
                If Not (Mid(sTime, i, 1) Like "[0-9]") Then
                    Exit For
                End If
            Next i
            timeUnitCount _
                = CLng(Mid(sTime, i + 1, identifierPos - i - 1))
            thisDate = thisDate _
                + timeUnitCount * timeUnitDateValue(iTimeUnit)
        Else
            ' Identifier not found. Do nothing.
        End If

    Next iTimeUnit

    ParseDateTime = thisDate
End Function

答案 1 :(得分:2)

此公式适用于您的所有示例

=SUM(MID(0&A1&"0000",FIND({"s","m","h","d"},0&A1&"xxsmhd")-2,2)/{86400,1440,24,1})

假设单元格A1中的数据,格式化结果单元格为[h]:mm:ss

如果您的单个数字值不在开头,则会失败,因此,如果您有12h03min可以,但如果您有12h3min则公式将失败。我可以解决这个问题,但是......

答案 2 :(得分:0)

示例:7周31天24小时60分钟

公式:

= ((IFERROR(VALUE(MID(J2,IF((FIND("weeks",A1)-3)=0,1,
(FIND("weeks",A1)-3)),2)),0))*(60*60*7*24))+
   ((IFERROR(VALUE(MID(A1,IF((FIND("days",A1)-3)=0,1,
(FIND("days",A1)-3)),2)),0))*(60*60*24))+
   ((IFERROR(VALUE(MID(A1,IF((FIND("hours",A1)-3)=0,1,
(FIND("hours",A1)-3)),2)),0))*(60*60))+
   ((IFERROR(VALUE(MID(A1,IF((FIND("minutes",A1)-3)=0,1,
(FIND("minutes",A1)-3)),2)),0))*(60))