将包含小时,分钟,秒的字符串转换为十进制小时

时间:2011-12-06 09:11:58

标签: excel vba excel-vba

我有一个自动生成的Excel工作表,其中包含一个包含表示时间跨度的字符串值的列。值具有以下格式:

17 hours, 6 minutes, 16 seconds

我需要将它们转换为显示小数小时(例如17.1小时)。我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:15)

您不必使用VBA。这个工作表公式将起到作用。

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

这将删除“seconds”字符串,并用:字符替换“hours”和“minutes”分隔符字符串。 VALUE然后将其解释为日期/时间,评估为一天的一小部分;所以对于你的“17小时,6分钟,16秒”的例子,0.712685185天。将此乘以24得出小数小时,即17.1044。

为了使这个更加健壮,你可以从SUBSTITUTE开始,但是上面给出了一般的想法。

如果你必须在VBA中这样做,那么我会这样做:

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.

答案 1 :(得分:2)

可能有更好的方法,但这是一种方法。

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)