I have a random word generator that will pull a word at random from a list every 7 seconds.
My button to stop this word generator returns the 1004 error and the Method 'OnTime' of object '_Application' failed.
Below are the codes for both buttons. Stop macro is from the OnTime page on Microsoft
Sub RandoWord()
Dim rw As Long
rw = [RandBetween(2,1526)]
Cells(3, 4) = Cells(rw, 1)
Application.OnTime Now TimeValue("00:00:07"), "RandoWord"
End Sub
Sub StopRandoWord()
Application.OnTime Now TimeValue("00:00:07"), _
Procedure:="RandoWord", Schedule:=False
End Sub
CodePudding user response:
You need to store the exact time of the next run if you want to cancel it.
Dim NextRun
Sub RandoWord()
Dim rw As Long
rw = [RandBetween(2,1526)]
Cells(3, 4) = Cells(rw, 1) 'really needs a specific worksheet...
NextRun = Now TimeValue("00:00:07")
Application.OnTime NextRun, "RandoWord"
End Sub
Sub StopRandoWord()
If NextRun>0 Then
Application.OnTime NextRun, Procedure:="RandoWord", Schedule:=False
NextRun = 0
End If
End Sub