I have a small “Job Timer” that allows me to see how long I have spent on a job, and how long I have left to complete a job. It looks like this:
The time spent on the job is correct, it works fine, however, the time remaining takes the start time of the job, adds the allocated job time to it and produces an “End Time”. When I subtract the current time (Now()
) from the “End Time”, I get strange results.
Here is my code:
Public dismissed As Boolean
Public TimeUpdate As Integer
Public Function TimeSpent( _
Optional TimeStarted As Variant, _
Optional Allocated As Variant, _
Optional TU)
If Not IsMissing(TimeStarted) Then
TimeSpent = Now() - TimeValue(TimeStarted)
End If
End Function
Public Function Remaining( _
Optional TimeStarted As Variant, _
Optional Allocated As Variant)
If Not IsMissing(Allocated) And Not IsMissing(TimeStarted) Then
EndTime = TimeValue(Allocated) + TimeValue(TimeStarted)
Remaining = EndTime - Now()
End If
End Function
Public Sub TS()
x = Now() + TimeSerial(0, 0, 1)
TimeSpentForm.Spent.Caption = TimeSpent(Job.StartTime1.Value, Job.ACT.Value, TimeUpdate)
TimeSpentForm.Spent.Caption = Format(TimeSpentForm.Spent.Caption, "hh:mm:ss")
TimeSpentForm.Remaining.Caption = Remaining(Job.StartTime1.Value, Job.ACT.Value)
TimeSpentForm.Remaining.Caption = Format(TimeSpentForm.Remaining.Caption, "hh:mm:ss")
If dismissed = False Then
Application.OnTime x, "TS"
End If
End Sub
When routine TS
is called for, the timer starts and the form is displayed, the routine will continue to run until the dismiss button is pressed (this works fine). But somewhere along the way the code goes wrong and instead of counting down from “1:00:00” (which is the allocated time in this particular case), it subtracts the “1:00:00” and goes to “23:00:00” and then counts up.
I’ve had serious issues with how VBA handles times and dates before in this manner, is there something obvious I’m missing here?
Thanks
Use =Time()
instead of Now
Now
will return current date as well as time (DateTime) whereas Time()
returns only the time portion.
(not relevant, but similarly =Date()
returns only the date portion of Now()
)
Edit: Also, as additional reference in understanding the implementation of date/time, do note BlackHawk’s comments below.
Tags: date, excelexcel, time