Convert a string containing hours, minutes, seconds to decimal hours

后端 未结 2 1400
臣服心动
臣服心动 2020-12-20 09:47

I have an automatically generated Excel sheet that has a column containing string values representing time spans. The values have the following format:

17 ho         


        
相关标签:
2条回答
  • 2020-12-20 10:10

    There may be better ways, but this is one way of doing it.

    hours = Trim(Split(timeString, "hours,")(0))
    minutes = Trim(Split(Split(timeString, "hours,")(1), " minutes,")(0))
    seconds = Trim(Split(Split(Split(timeString,"hours,")(1)," minutes,")(1), "seconds")(0))
    
    TimeInPercentage = CInt(hours) + (1/60) * (CInt(minutes)) + (1/3600) * CInt(seconds)
    
    0 讨论(0)
  • 2020-12-20 10:17

    You don't have to use VBA. This worksheet formula will do the trick.

    =24*VALUE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(B4," hours, ",":"),
         " minutes, ",":")," seconds",""))
    

    This deletes the "seconds" string and replaces the "hours" and "minutes" delimiter strings with the : character. VALUE then interprets this as a date/time, which evaluates to a fraction of a day; so for your "17 hours, 6 minutes, 16 seconds" example, 0.712685185 days. Multiplying this by 24 gives decimal hours, i.e. 17.1044.

    To make this more robust, you could start by SUBSTITUTEing out the spaces, but the above gives you the general idea.

    If you must do it in VBA, then I would do it like this:

    Dim myTimeString As String
    Dim splitTime() As String
    Dim decimalHours As Double
    
    myTimeString = "17 hours, 6 minutes, 16 seconds"
    
    ' Remove useless characters
    myTimeString = Trim(Replace(Replace(Replace(myTimeString, " ", ""), _
        ",", ""), "seconds", ""))
    ' Replace "hours" and "minutes" by a useful delimiter, ":"
    myTimeString = Replace(Replace(myTimeString, "minutes", ":"), "hours", ":")
    ' String now looks like this: "17:6:16". Now split it:
    splitTime = Split(myTimeString, ":")
    
    decimalHours = CInt(splitTime(0)) + CInt(splitTime(1)) / 60 + _
        CInt(splitTime(2)) / 3600
    
    
    ' Alternatively, convert the string to a date, then to decimal hours
    Dim myDate As Date
    myDate = CDate(myTimeString)
    decimalHours2 = 24 * CDbl(myDate) ' same result.
    
    0 讨论(0)
提交回复
热议问题