I'm having problems with a runtime 1004 error in VBA. I made a time registration tool, to measure time needed for specific actions. The weird thing is, that the code works perfectly 9 out of 10 times. Just that 1 out of 10 times it generates this runtime error. I cannot see what is causing this problem! I don't do anything different, yet it generates this error once in a while....
I did google and searched for this runtime error in combination with the Application.Ontime function, but I think its defined the way it should? Below is the code, which I in turn found somewhere else on the net. There is a worksheet with commandbuttons (each for a specific activity) and once pressed, the StartTimer procedure is called (in a seperate module), press again and the StopTimer procedure (in a seperate module) is called. The error is (sometimes) generated in the StopTimer sub.
Public StartTime As Single
Public FinalTime As Single
Sub starttimer()
Application.OnTime Now + TimeValue("00:00:01"), "nexttick"
End Sub
Sub Nexttick()
Sheet1.Range("y2").Value = Sheet1.Range("y2").Value + TimeValue("00:00:01")
starttimer
End Sub
Sub Stoptimer()
With ThisWorkbook.Worksheets("Home")
Application.OnTime Now + TimeValue("00:00:01"), "nexttick", , False
End With
Sheets("Log").Range("c10000").End(xlUp).Offset(1, 0) = Format(Sheet1.Range("y2").Value, "h:mm:ss")
Sheets("Home").Range("y2").Value = 0
End Sub
Its driving me nuts, especially since it works most of the time! Hope someone can help me out here :)
Thanks in advance!!
Bart
The [Earliest Time] value should be the same as originally set when scheduling the sub to False
. Times are rounded to the nearest second which is why you're probably getting away with it sometimes. Seeing as you assign the value of the time to a cell, reference that cell instead of setting the time in your code:
Public StartTime As Single
Public FinalTime As Single
Sub starttimer()
StartTime = Now + TimeValue("00:00:01")
Application.OnTime StartTime, "nexttick"
End Sub
Sub Nexttick()
Sheet1.Range("y2").Value = Sheet1.Range("y2").Value + TimeValue("00:00:01")
starttimer
End Sub
Sub Stoptimer()
With ThisWorkbook.Worksheets("Home")
Application.OnTime StartTime, "nexttick", , False
End With
Sheets("Log").Range("c10000").End(xlUp).Offset(1, 0) = Format(Sheet1.Range("y2").Value, "h:mm:ss")
Sheets("Home").Range("y2").Value = 0
End Sub
Reference: Application.OnTime Method (Excel)
The value of EarliestTime is rounded to the closest second.
Set Schedule to false to clear a procedure previously set with the same Procedure and EarliestTime values.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.