Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

excel

vba

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.

like image 586
Sam Avatar asked Jun 21 '12 17:06

Sam


3 Answers

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

  x = Application.Text(.294,"[h]:mm")
like image 169
Joel Spolsky Avatar answered Oct 05 '22 09:10

Joel Spolsky


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
like image 30
Tim Williams Avatar answered Oct 05 '22 08:10

Tim Williams


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

like image 43
SeanC Avatar answered Oct 05 '22 09:10

SeanC