Converting Time Formats in Excel

↘锁芯ラ 提交于 2019-11-26 18:39:51

问题


How would I convert time values that are output in as a string (21m49s) into the Excel time value (00:21:49)? If there is no hour value to be given, the cell is not assigned a 0h value. It will display only minutes and seconds in that case.

Will also need to account for readings above 60 minutes which would display as 1h34m14s.

This is how I receive the time values:

This is what I need them to look like:


回答1:


Try this:

=TIME(IF(ISNUMBER(FIND("h",A1)),LEFT(A1,FIND("h",A1)-1),0),IF(ISNUMBER(FIND("m",A1)),IF(ISNUMBER(FIND("h",A1)),MID(A1,FIND("h",A1)+1,FIND("m",A1)-1-FIND("h",A1)),LEFT(A1,FIND("m",A1)-1)),0),IF(ISNUMBER(FIND("s",A1)),IF(ISNUMBER(FIND("m",A1)),MID(A1,FIND("m",A1)+1,LEN(A1)-1-FIND("m",A1)),LEFT(A1,FIND("s",A1)-1)),0))


Though @Jeeped beat me, I will post my UDF:

Function TimeChange(str As String) As Date
Dim strArr() As String
Dim i As Integer
Dim hr As Integer
Dim min As Integer
Dim sec As Integer

str = Replace(str, "h", "h ")
str = Replace(str, "m", "m ")
str = Replace(str, "s", "s ")

strArr = Split(Trim(str))

For i = 0 To UBound(strArr)
    Select Case Right(strArr(i), 1)
        Case "h": hr = Left(strArr(i), Len(strArr(i)) - 1)
        Case "m": min = Left(strArr(i), Len(strArr(i)) - 1)
        Case "s": sec = Left(strArr(i), Len(strArr(i)) - 1)
    End Select
Next i

TimeChange = TimeSerial(hr, min, sec)

End Function




回答2:


Possibly as a VBA UDF¹.

Function realTime(str As String) As Double
    Dim t As Long, vTMs As Variant, vTMP As Variant

    vTMs = Array("h", 0, "m", 0, "s", 0)
    vTMP = Array(str & ChrW(8203))

    For t = LBound(vTMs) To UBound(vTMs) Step 2
        vTMP = Split(vTMP(0), vTMs(t))
        If IsNumeric(vTMP(0)) Then
            vTMs(t + 1) = Int(vTMP(0))
            vTMP(0) = vTMP(1)
        End If
    Next t

    realTime = TimeSerial(vTMs(1), vTMs(3), vTMs(5))

End Function

        


¹ A User Defined Function (aka UDF) is placed into a standard module code sheet. Tap Alt+F11 and when the VBE opens, immediately use the pull-down menus to Insert ► Module (Alt+I,M). Paste the function code into the new module code sheet titled something like Book1 - Module1 (Code). Tap Alt+Q to return to your worksheet(s).



来源:https://stackoverflow.com/questions/36292174/converting-time-formats-in-excel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!