为什么DateDiff返回一个日期而不是分钟数?

Roy*_*yce 2 excel vba

我需要找出两个字符串之间存在多少分钟。

h1 = TimeValue("06:00:00")
h2 = TimeValue("22:00:00")
res = DateDiff("n", h1, h2)
Run Code Online (Sandbox Code Playgroud)

但是,res = 17/08/1902,而预期结果是960。

Sub calcul(hours As Variant, Optional n As Integer = 0)
    i = 3
    Do While (Cells(i, 0) <> "")
        Dim res As Date
        Dim h2 As Date
        Dim h1 As Date
        Dim h As Integer

        If (n = 0) Then
           h = 0
        Else
           h = Cells(i, 7).Value - 1
        End If

        h1 = TimeValue(hours(h)("h1"))
        h2 = TimeValue(hours(h)("h2"))
        res = DateDiff("n", h1, h2)

        ...
Run Code Online (Sandbox Code Playgroud)

Fox*_*rns 8

这里的问题是你如何定义res

日期和时间值是数字。即使您实际上将其视为30/09/201912:00:00,对于Excel,两种情况都是数字。

Excel可以正确识别的第一个日期是01/01/1900,整数值是1。数字2是02/01/1900,依此类推。实际上,今天是43738。

时间是相同的,但小数部分是小时,分钟和秒。0,5表示12:00:00。因此,实际上,43738,5意味着30/09/2019 12:00:00

无论如何,对于您而言,您获得的时差为2分钟(以分钟为单位)。结果是960,但是您将这个值赋给了一个date类型,因此960被转换为17/08/1902。

Dim h1 As Date
Dim h2 As Date
Dim res As Single


h1 = TimeValue("06:00:00")
h2 = TimeValue("22:00:00")
res = DateDiff("n", h1, h2)

Debug.Print res
Run Code Online (Sandbox Code Playgroud)

上面的代码将960正确返回。使其适应您的需求。

更新:因为DateDiff返回一个Long,所以定义resas Single 根本不值得。我这样做的原因是,在很多情况下,使用时间需要小数点,但是如果您使用just DateDiff,则可以完美地执行res as Longor res as Integer

使用简单的代码注意 DateDiff和普通减法之间的区别

Dim time1 As Date
Dim time2 As Date
Dim res1 As Integer
Dim res2 As Single 'or double if you wish

time1 = "06:00:00"
time2 = "06:30:30"

'time difference between these 2 values are 30 minutes and 30 seconds (30,5 minutes in decimal)

res1 = DateDiff("n", time1, time2)
res2 = (time2 - time1) * 1440 '1440 is the number of minutes in a whole day

Debug.Print "With DateDiff:" & res1, "Normal: " & res2
Run Code Online (Sandbox Code Playgroud)

此代码的输出是: With DateDiff:30 Normal: 30,5

DateDiff有时不值得使用。根据您需要的结果的准确性,是否DateDiff可以补偿。我建议您尽量避免这样做(这是我的看法)

希望这可以帮助

更新2:关于上面的代码,是的,可以使用一种解决方案将DateDiff("s", time1, time2) / 60秒转换为分钟,但是由于小数,该值应该分配给允许该值的数据类型。