2015-04-03 85 views
0

我想從時間戳中減去任何秒,其類型爲Double如何從雙倍的時間戳中減去秒數?

下面是我想象的功能:

Function subtractSeconds() 

Dim timeStamp As Double 
Dim timeStampSeconds As Double 

timeStamp = Cells(1, 1) 
'timeStampSeconds = getSeconds(timeStamp) 

'Cells(1, 1) = timeStamp - timeStampSeconds 

End Function 

這裏是我到目前爲止,與comments幫助。我當然要找的東西更優雅:

Function subtractSeconds() 

Dim timeStamp As Double 
Dim timeStampHours As Long 
Dim timeStampMinutes As Long 
Dim timeStampSeconds As Long  

timeStamp = Cells(1, 1) 

Cells(1, 1) = Format(Cells(1, 1), "yyyy/m/d hh:mm:ss") 
timeStampHours = DatePart("h", Cells(1, 1)) 
timeStampMinutes = DatePart("m", Cells(1, 1)) 
'timeStampSeconds = DatePart("s", Cells(1, 1)) 

'something like the following to put the date time back together without seconds 
'Cells(1, 1) = Format(Cells(1, 1), "yyyy/m/d") & TimeValue(timeStampHours & ":" & timeStampMinutes & ":" & 0)) 

'Convert back to double 

End Function 
+2

查找功能'DartPart'它允許你提取包括秒的日期時間的任何部分。 – 2015-04-03 08:19:25

+0

'DatePart'?看起來很有希望!謝謝! – 2015-04-03 08:20:56

回答

2

如果你能Format()Cells(1, 1),那麼它包含恰好被格式化爲一個數呈現一個有效的VBA日期。

此時你需要

Cells(1, 1).Value = DateAdd("s", -DatePart("s", Cells(1, 1).Value), Cells(1, 1).Value) 

然而,這將數的單元格中的外觀更改爲日期,即使它仍然會被存儲爲一個數字。如果你想保持多項外觀,使用Value2

Cells(1, 1).Value2 = DateAdd("s", -DatePart("s", Cells(1, 1).Value2), Cells(1, 1).Value2) 
+0

輝煌。這麼多有用的功能我不知道。我一回到繪圖板就會測試它。我實際上更喜歡將數字格式化爲日期,但「Value2」似乎非常有用。 – 2015-04-03 12:50:32