我不能使用datediff vba

时间:2015-04-01 08:58:41

标签: vba excel-vba excel-2007 excel

示例输入:

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

当我使用

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

产生错误:type mismatch

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

尝试使用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函数的最小单位是秒。

答案 1 :(得分:0)

看起来你还没有成功的答案,所以这里有可能。

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)