【问题标题】:How do I format Time in [h]:mm excel format using format() function in VBA如何使用 VBA 中的 format() 函数以 [h]:mm excel 格式格式化时间
【发布时间】:2012-06-21 17:42:13
【问题描述】:

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

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

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

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

这些都没有预期的效果。我还查看了 MS 帮助,但找不到任何有用的信息。

【问题讨论】:

  • 你得到的是什么而不是你期望得到的? datetime 是如何声明的,它是如何填充的?
  • datetime 只是一个双变量。并且函数给出不同的结果。 hh:mm 是最接近的,但只给出最多 24 小时的小时数,25 小时显示为 01:00

标签: vba excel


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    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
    

    【讨论】:

    • 感谢您花时间写这篇文章。这是一个非常好的解决方案,我投了赞成票。
    【解决方案3】:

    不带格式化功能,但可以使用Range(MyData).NumberFormat = "[h]:mm"

    【讨论】:

      【解决方案4】:

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

      这个自制函数可以解决问题:

      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
      

      【讨论】:

      • 嗨。谢谢你,这是实现我需要的好方法。我投了赞成票,但我将接受 Application.Text 方法,因为它更简洁一些。山姆
      猜你喜欢
      • 1970-01-01
      • 2016-11-09
      • 1970-01-01
      • 2012-10-30
      • 1970-01-01
      • 2010-12-26
      • 1970-01-01
      • 1970-01-01
      • 2013-09-21
      相关资源
      最近更新 更多