【问题标题】:I can't use datediff vba我不能使用 datediff vba
【发布时间】:2015-04-01 08:58:40
【问题描述】:

示例输入:

date1 = "2015-03-23 07:06:17.855000"
date2 = "2015-03-23 07:06:17.870000"

当我使用时

ans = datediff("s", date1, date2)

它会产生错误:type mismatch

我该如何解决这个问题?

【问题讨论】:

    标签: vba excel excel-2007


    【解决方案1】:

    您似乎还没有得到成功的答案,所以这里有一个可能性。

    Dim t() as string
    Dim d1 as long
    Dim d2 as long
    
    date1 = "2015-03-23 07:06:17.855000"
    date2 = "2015-03-23 07:06:17.870000"
    t = split(date1, ".")   'use the "." to split off the miliseconds
    d1 = clng(t(2))         'grab the milliseconds, convert it to long
    t = split(date2, ".")   'use the "." to split off the miliseconds from the other date
    d2 = clng(t(2))         'grab the milliseconds, convert it to long
    
    msgbox "Difference in milliseconds: " & cstr(d2-d1)
    

    【讨论】:

      【解决方案2】:

      尝试使用CDate("string_date")将存储为字符串的日期转换为日期数据类型:

      Dim date1 As String, date2 As String, ans As Long
      
      date1 = "2015-03-23 07:06:17.855000"
      date2 = "2015-03-23 07:06:17.870000"
      ans = datediff("s", CDate(Left(date1, Len(date1)-7)), CDate(Left(date2, Len(date2)-7)))
      'returns 0, because both date and parts are the same!
      

      DateDiff函数的最小单位是秒。

      【讨论】:

      • 我现在看到了。 DateDiff 函数可以返回以秒为单位的时差,但真正的时差是以毫秒为单位的。 DateDiff 函数无法比较,因为最小单位是一秒。当您以这种方式传递日期参数时:CDate(Left(date1, Len(date1)-7) 它将执行而不会出错。
      • @Maciej Los ans 可能必须很长,而且你的括号数不出来,7-"(" 并且只有 6-")"
      • @Davesexcel,有趣的问题和答案,但是 - 正如我所提到的 - 通过 DateDiff 函数获取毫秒是不可能的。
      • @Maciej Los-我没有问问题,我提供了毫秒问题的链接并向您解释您的代码没有足够的右括号,并且“ans”应该是长
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-27
      • 2011-12-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-25
      • 2020-03-29
      相关资源
      最近更新 更多