2015-10-19 28 views
1

我在分鐘內獲取兩個日期之間的詳細或特定差異時遇到問題。比方說:VBA在小時內獲取特定的差異

Date Start : 24/7/2015 12:38:00 PM 
Date End : 27/7/2015 12:12:00 PM 

我的代碼確實給這兩個日期之間的差異,但實際上並沒有具體的,這意味着它使兩個日期之間的3天差異,但不只是我想要的(比方說,它們的區別在於68小時30分鐘56秒)。那麼,我該怎麼做?

這裏是我的代碼:

Date1 = DateValue(CurrentSheet.Cells(PRow, "U").Value) 
Date2 = DateValue(CurrentSheet.Cells(PRow, "S").Value) 

FRow = CurrentSheet.UsedRange.Cells(1).Row 
lrow = CurrentSheet.UsedRange.Rows(CurrentSheet.UsedRange.Rows.count).Row 

For PRow = lrow To 2 Step -1 
    CurrentSheet.Cells(PRow, "AD").Value = DateDiff("d", Date2, Date1) 'produce days 
    CurrentSheet.Cells(PRow, "AE").Value = DateDiff("h", Date2, Date1) 'produce hours 
    CurrentSheet.Cells(PRow, "AF").Value = DateDiff("n", Date2, Date1) 'produce minutes 
Next PRow 

目前,我得到了答案:

3天,

72小時(3次24小時),

1440分鐘(24周小時時間60分鐘)。

回答

-1

其實很簡單!我從來沒有想過這種方式可以像我想要的那樣產生答案! :)

昏暗長得更高只要 昏暗lrow只要 昏暗船頭只要

Range("AD1").Value = "Hours Differences" 

Dim CurrentSheet As Worksheet 
Set CurrentSheet = Excel.ActiveSheet 

FRow = CurrentSheet.UsedRange.Cells(1).Row 
lrow = CurrentSheet.UsedRange.Rows(CurrentSheet.UsedRange.Rows.count).Row 

For PRow = lrow To 2 Step -1 
CurrentSheet.Cells(PRow, "AD").Value = (CurrentSheet.Cells(PRow, "U").Value - CurrentSheet.Cells(PRow, "S").Value) * 24 
Next PRow 

它會產生71.5666666666511。我被DATE格式分散注意力。感謝所有幫助!:d

+0

只需添加CurrentSheet.Cells(船頭, 「AD」)值= ROUND(((CurrentSheet.Cells(船頭, 「U」)值 - 。CurrentSheet.Cells(船頭, 「S」)值)* 24), 2)變成2位小數。 – IlhamideaZ

1

原因是,您使用的功能DateValue只能將值轉換爲日期(時間部分被刪除)。

因此,這些日期:

Date Start : 24/7/2015 12:38:00 PM 
Date End : 27/7/2015 12:12:00 PM 

DateValue功能處理它們後變成了:

Date Start : 24/7/2015 00:00:00 
Date End : 27/7/2015 00:00:00 

[編輯]

你需要將它們轉換爲Date類型。

您可以使用VBA內置函數CDate做到這一點:

Date1 = CDate(CurrentSheet.Cells(PRow, "U").Value) 
Date2 = CDate(CurrentSheet.Cells(PRow, "S").Value) 
+0

那麼,到什麼類型的,我必須轉換爲? – IlhamideaZ

0

在內部,日期是1月以來-1-1900(或1902年,在其實並不重要)存儲的天數。這意味着1 day = 1,這也意味着1 hour = 1/24
所以,如果我正確地理解你的問題,以獲得天的差別,時間,日期2和DATE1分鐘之間,你可以使用

daysdiff = DateDiff("d", Date2, Date1) 
hoursdiff = INT((Date2-date1-Daysdiff)/24) 
'or 
hoursdiff = DateDiff("h", Date2-daysdiff, Date1) 
minutesdiff = Datediff("n", Date2-daysdiff-hoursdiff/24, Date1) 

對不起,沒有測試過,但你的想法。


編輯:你還應該在你裏面包含@mielk言論的變化。