2012-03-29 161 views
2

我有一個用戶表單,要求用戶通過兩個單獨的組合框cboStartDate,cboStartTime輸入特定的日期和時間。用戶還必須在文本字段txtDuration中輸入持續時間。Excel VBA將時間特定值存儲到用戶表單的單元格中

保存後,開始日期和時間將被存儲在格式化的單元格中[DD/MM/YYYY HH:MM AM/PM]。結束日期和時間將根據持續時間字段計算並存儲在具有相同格式的另一個單元格中。例如:

 
+-----------------------+-----------------------+ 
| startTime    | endTime    | 
+-----------------------+-----------------------+ 
| 2/4/2012 11:30:00 AM | 2/4/2012 2:00:00 PM | 
+-----------------------+-----------------------+ 

但是,在運行完用戶表單後,不存儲開始時間,並且不計算結束時間。事情是這樣的:

 
+-----------------------+-----------------------+ 
| startTime    | endTime    | 
+-----------------------+-----------------------+ 
| 2/4/2012 12:00:00 AM | 2/4/2012 12:00:00 AM | 
+-----------------------+-----------------------+ 

下面是我的我的VBA代碼部分:

Dim iRow As Long 
Dim ws As Worksheet 
Dim startDate As Date 
Dim unFmtStartDuration() As String 
Dim startDuration As Double 
Dim minTest As Integer 
Dim endDate As Date 
Dim endDuration As Double 

Set ws = Worksheets("EVENTS") 

'Search for the last row in the worksheet 
iRow = ws.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row 

'Date manipulation and set start and end timings 
unFmtStartDuration() = Split(cboStartTime.Text, ":") 
startDuration = unFmtStartDuration(0) 
If unFmtStartDuration(1) = "00" Then 
    minTest = 0 
Else 
    minTest = unFmtStartDuration(1) 
    If minTest = 30 Then 
     startDuration = startDuration + 0.5 
    End If 
End If 
startDate = DateValue(DateAdd("h", startDuration, cboDate.Text & " 12:00AM")) 
ws.Cells(iRow, 4).Value = startDate 
endDuration = txtDuration.Value 
endDate = DateValue(DateAdd("h", endDuration, startDate)) 
ws.Cells(iRow, 5).Value = endDate 

所以,我怎樣才能得到這部分整理出來?希望在這裏得到任何幫助。謝謝。

P.S.想在這裏張貼截圖,但是我的名聲太低了。抱歉。

回答

2

看起來你只是增加了時間minTest = 30,但這個值可能會有很大的不同。另外,在一個實例中,當引用unFmtStartDuration時,您正在比較字符串和另一個數字,這可能有用,但在閱讀代碼時會令人困惑。

要遵循當前的方法,使用

startDuration = Val(unFmtStartDuration(0) + Round(Val(unFmtStartDuration(1))/60, 2) 

替換此

startDuration = unFmtStartDuration(0) 
If unFmtStartDuration(1) = "00" Then 
    minTest = 0 
Else 
    minTest = unFmtStartDuration(1) 
    If minTest = 30 Then 
     startDuration = startDuration + 0.5 
    End If 
End If 

這將採取任何的時間,並將其轉換到你所使用的十進制的形式,而不是依靠30比賽。 (除非你需要明確,如果是這樣,所以說,我覺得這個還是可以安排與四捨五入技巧。)

不過,我認爲更好的選擇是使用

startDuration = TimeValue(cboStartTime.Text) * 24 

因此,沒有涉及其他數學或檢查。

此外,除非cboStartTime.Text(隨後startDuration)大於24小時,這

startDate = DateValue(DateAdd("h", startDuration, cboDate.Text & " 12:00AM")) 

將始終返回在cboDate.Text有一個隱含的12:00:00 AM指定的日期。爲了解決這個問題,你會想改變

startDate = DateAdd("h", startDuration, cboDate.Text & " 12:00AM") 

我認爲有一些更多的修復,但希望這可以讓你在正確的方向前進......

+0

感謝您的快速答覆!我最初並沒有考慮'TimeValue()'函數,因爲我對使用VBA很陌生。用它在代碼和它的美麗。儘管如此,感謝您的幫助!它現在運行得很好......順便說一下,'DateAdd'函數由於某些原因不能在h中添加0.5 ...因此採用將startTime和endTime分解爲幾小時和幾分鐘來代替快速修復。附:希望我可以upvote,再次代表太低... :( – 2012-03-29 16:42:55

+0

+1不錯的一個加菲:) – 2012-03-29 17:53:24

+0

謝謝,@SiddharthRout。別擔心羅伯特;堅持下去,你會在代表處站起來。 :-) – Gaffi 2012-03-29 18:29:13

相關問題