2016-12-18 257 views
2

我想顯示使用vba的兩個時間戳之間的天數或小時數或分鐘或秒數。VBA鍛鍊兩個時間戳之間有多少天,幾小時,幾分鐘或幾秒鐘?

到目前爲止,我的代碼給了我幾小時或幾天。

Sub Date_Dif() 

    Dim d1 As Date 
    d1 = Range("A8").Value 

    Dim d2 As Date 
    d2 = Now 

    Dim hrsDiff As Long 
    hrsDiff = DateDiff("h", d1, d2) 

    ActiveSheet.Range("Z5").Value = IIf(hrsDiff >= 24, _ 
       hrsDiff \ 24 & " days " & hrsDiff Mod 24 & " hours", _ 
       hrsDiff & " hours") 

End Sub 

我該如何適應這個給我幾分鐘或幾秒?

在此先感謝

回答

4

最簡單的方法是減去日期和使用HourMinute,並Second功能。由於Date變量存儲爲代表紀元以來的天整數部分Double,可以減法後直接使用,對天:

Dim diff As Date 
diff = Now - #7/7/2016 2:15:16 PM# 
Debug.Print CLng(Int(diff)) & " days" 
Debug.Print Hour(diff) & " hours" 
Debug.Print Minute(diff) & " minutes" 
Debug.Print Second(diff) & " seconds" 

把它插入到你的Sub,你會得到這樣的事情:

Sub Date_Dif() 

    Dim d1 As Date 
    d1 = Range("A8").Value 

    Dim diff As Date 
    diff = Now - d1 

    ActiveSheet.Range("Z5").Value = _ 
       CLng(Int(diff)) & " days " & _ 
       Hour(diff) & " hours " & _ 
       Minute(diff) & " minutes " & _ 
       Second(diff) & " seconds" 
End Sub 
相關問題