How do I format Time in [h]:mm excel format using format() function in VBA

笑着哭i 提交于 2020-01-03 07:28:14

问题


Is it possible to format time in [h]:mm format using VBA?

[h]:mm format in excel would show 25 hours as 25:00, 125 hours as 125:00

I've tried several things such as:

format(datetime, "[h]:mm")
format(datetime, "H:mm")
format(datetime, "hh:mm")

None of these have the desired effect. I've also had a look through the MS help and can't find anything useful.


回答1:


Use the TEXT worksheet function via the application object, as so:

  x = Application.Text(.294,"[h]:mm")



回答2:


JFC beat me to it, but here's what I came up with anyway...

Sub Test()
    Debug.Print FormatHM(24 / 24)       '24:00
    Debug.Print FormatHM(25 / 24)       '25:00
    Debug.Print FormatHM(48 / 24)       '48:00
    Debug.Print FormatHM(48.6 / 24) '48:36
End Sub

Function FormatHM(v As Double) As String
    FormatHM = Format(Application.Floor(v * 24, 1), "00") & _
                 ":" & Format((v * 1440) Mod 60, "00")

End Function



回答3:


not with the format function, but you can use Range(MyData).NumberFormat = "[h]:mm"




回答4:


It looks like VBA's Format function has no built-in way of doing this. (Eyes rolling.)

This home-made function will do the trick:

Function HoursAndMinutes(datetime As Date) As String
    Dim hours As Integer
    Dim minutes As Integer
    hours = Int(datetime) * 24 + Hour(datetime) ' the unit of Date type is 1 day
    minutes = Round((datetime * 24 - hours) * 60)
    HoursAndMinutes = hours & ":" & Format(minutes, "00")
End Function

Usage:

    Dim datetime As Date
    datetime = TimeSerial(125, 9, 0) ' 125 hours and 9 minutes
    Debug.Print HoursAndMinutes(datetime) ' 125:09


来源:https://stackoverflow.com/questions/11143746/how-do-i-format-time-in-hmm-excel-format-using-format-function-in-vba

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