2015-04-01 32 views
0

例輸入:當我使用我不能使用DATEDIFF VBA

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

它產生錯誤

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

type mismatch

我該如何解決這個問題?

回答

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) 
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功能的最小單位是一秒鐘。

+0

是的,我試過,但它不工作 – Aoon 2015-04-01 09:26:04

+0

我現在看到它。 DateDiff函數可以以秒爲單位返回時間差,但真正的差異以毫秒爲單位。 'DateDiff'函數無法比較它,因爲最小的單位是秒。當你通過日期參數這種方式:'CDate(Left(date1,Len(date1)-7)'它會執行沒有錯誤 – 2015-04-01 09:45:10

+0

@Maciej洛杉磯可能要很長,並且你的括號是超出計數, 「(」和只有6-「)」 – Davesexcel 2015-04-01 10:38:22