双倍时间格式VBA

时间:2017-06-10 11:19:21

标签: vba time format double

在乞讨时我想告诉你我刚刚读了很多关于它的堆栈而且我没有找到解决方案......

我减去了两个日期 1 - 2017/05/05 17:00 2 - 2017/05/09 18:00

我希望收到" 4天1小时" 我应该怎么做?我尝试使用DateFormat / Format / DateDiff和很多东西。

1 个答案:

答案 0 :(得分:0)

它并不总是必须是现成的VBA功能。特别是对于日期,我很少找到我想要的VBA准备好的东西。试试这个自定义功能:

Function myDateDiff(ByVal d1 As Date, ByVal d2 As Date) As String
  Dim days As Long, hours As Long
  days = DateDiff("d", d1, d2)               ' diff in days
  hours = DateDiff("h", d1, d2) - days * 24  ' diff in hours
  myDateDiff = days & " Day" & IIf(days > 1, "s ", " ") & hours & " Hour" & IIf(hours > 1, "s", "")
End Function
Sub Test()
    Dim d1 As Date, d2 As Date
    d1 = CDate("2017/05/05 17:00")
    d2 = CDate("2017/05/09 18:00")
    Debug.Print myDateDiff(d1, d2)    ' 4 Days 1 Hour

    d1 = CDate("2017/05/05 17:00")
    d2 = CDate("2017/05/06 19:00")
    Debug.Print myDateDiff(d1, d2)    ' 1 Day 2 Hours
End Sub