1

I'm using Excel 2010, and want to create a countdown timer in excel. The code will be started and stopped by using buttons with macros attached to them. The problem occurs when the "start" button is pushed. The code above is utilizing Cell "B1" as the input spot, because I was just trying to get it to work, but every time I tried, it would always say: "Cannot run the macro . The macro may not be available in this workbook or all macros may be disabled".

Yes I enabled all macros before putting this here. I want to be able to take user input, and to make that the time that the timer starts at instead of just using cell "B1".

'Macro for Starting the timer (attached to the start button)
Sub startTimer()
Application.OnTime Now + TimeValue("00:00:01"), "nextTick"
End Sub

'Macro for next second
Sub nextTick()
Sheet1.Range("B1").Value = Sheet1.Range("B1").Value - TimeValue("00:00:01")
startTimer
End Sub

'Macro for stopping the timer (attached to the end button)
Sub stopTimer()
Application.OnTime Now - TimeValue("00:00:01"), "nextTick", , False
End Sub
2
  • Is this code in a module code sheet or a sheet code sheet? Did you get there by right-clicking the worksheet's name tab and choose View Code? Did you open the VBE with [alt]+F11 and use the pull-downs to Insert ► Module? Commented May 11, 2016 at 21:18
  • @Jeeped It is in the main sheet Commented Sep 7, 2017 at 1:20

1 Answer 1

1

I modified your code very slightly and put it in a standard module:

Public Future As Double

Sub StartTimer()
    Future = Now + TimeSerial(0, 0, 1)
    Application.OnTime earliestTime:=Future, procedure:="nextTime", _
         schedule:=True
End Sub

Sub nextTime()
    Sheet1.Range("B1").Value = Sheet1.Range("B1").Value - TimeValue("00:00:01")
    StartTimer
End Sub

Sub StopTimer()
   On Error Resume Next
   Application.OnTime earliestTime:=Future, _
       procedure:="nextTime", schedule:=False
End Sub

Both StartTimer() and StopTimer() run just fine.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for taking the time to look at this, this works exactly as advertised.
I was wondering how I could get this to work during runtime, as in, i wanted to get user input and punch that in as a time variable, and then once all other modules were completed, then this module would be executed.
@MTB I wrote some code a while back to do exactly what you describe. The code requested the time in seconds and then used it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.