Converting Time Formats in Excel

后端 未结 2 733
无人及你
无人及你 2020-12-04 03:45

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

相关标签:
2条回答
  • 2020-12-04 04:30

    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).

    0 讨论(0)
  • 2020-12-04 04:45

    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
    

    0 讨论(0)
提交回复
热议问题