如何使用VBA中的format()函数来格式化:mm excel格式的时间

是否可以使用VBA格式化[h]:mm格式的时间?

在Excel中,[mm]格式将显示25小时为25:00,125小时为125:00

我已经尝试了几件事情,例如:

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

这些都没有预期的效果。 我也看过MS的帮助,找不到任何有用的东西。

通过应用程序对象使用TEXT工作表函数,如下所示:

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

JFC打败了我,但是这是我想出来的…

 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 

而不是格式化函数,但是你可以使用Range(MyData).NumberFormat = "[h]:mm"

看起来VBA的Format函数没有内置的方法。 (翻白眼。)

这个自制的function将诀窍:

 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 

用法:

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