1

I need to create a timer in Excel 2016 VBA editor that will go-off every second and display a message.

I have a simple code that will do just that; however when I run the code a message box appears and then an error follows. My code is presented below:

Private Sub Workbook_Open()
RunEveryTwoMinutes
End Sub

Sub RunEveryTwoMinutes()
MsgBox ("Stop!")
Application.OnTime Now + TimeValue("00:00:01"), "RunEveryTwoMinutes"
End Sub

The error I receive states: "Cannot run the macro 'C:user|generic\Book1.xlsm'. The macro may not be available in this workbook or all macros may be disabled.

I am not sure what is occurring. I simply need to find out a way to create a one second timer that initiates as soon as the code initializes.

1 Answer 1

1

Place this code in your workbook code module:

Private Sub Workbook_Open()
RunEveryTwoMinutes
End Sub

and place this code in a standard code module:

Sub RunEveryTwoMinutes()
MsgBox ("Stop!")
Application.OnTime Now + TimeValue("00:00:01"), "RunEveryTwoMinutes"
End Sub

Alternatively, you can have all the code in your Workbook code module, but you need to qualify the macro name:

Private Sub Workbook_Open()
RunEveryTwoMinutes
End Sub

Sub RunEveryTwoMinutes()
MsgBox ("Stop!")
Application.OnTime Now + TimeValue("00:00:01"), "ThisWorkbook.RunEveryTwoMinutes"
End Sub

I believe the first method is preferable.

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

3 Comments

Nice answer, but why do you prefer the function to be in a standard module?
@A.S.H - IMO it leads to less problems down the track if functions in the ThisWorkbook module are just specific to the workbook, and functions in forms are just specific to the form, and functions in worksheets are just specific to the worksheet, and functions in classes are specific to the class, and everything else gets put into generic modules.
That's a good point. Standard modules are also easier to export, hence to reuse. Kudos :)

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.