简体   繁体   中英

Excel Function 'Application.OnTime' still running after closing the workbook

I am using Excel (Office 365).

here is a video with my problem: link

The internet is full of examples where people say that the code should work when we set Schedule to False but sadly that did not help me.

The code should start a cycle using Application.OnTime and stop it before closing the workbook.

  • If I run the function stopF manually, in the VBA Editor, it stops Application.OnTime properly.
  • But if I close the workbook, it still opens up and continues executing Application.OnTime .
' In Module1:

Public startingTime  As Double

Sub startF()
    MsgBox "hello"
    startingTime = Now + TimeValue("00:00:10")
    Application.OnTime startingTime, "Module1.startF"
End Sub

Sub stopF()    'HERE IT WORKS GOOD
    On Error Resume Next
    Application.OnTime startingTime, "Module1.startF", , False
End Sub

' In ThisWorkbook:

Private Sub Workbook_BeforeClose(Cancel As Boolean)
 Call stopF   'HERE IT DOES NOT WORK GOOD
End Sub

I don't have a clue what could I do more.

My temporary solution to my question:

I left the whole code like it was and added into Module1 following code:

' In Module1:

Sub closeWorkbook()
    Call stopF
    ThisWorkbook.Close
End Sub

The point is:

  • for manual closing stopF called from Workbook_BeforeClose will work
  • for vba closing stopF called from a module will work.

A bit more detailed:

  • when a user closes a workbook manually (closes the Excel window) then Workbook_BeforeClose => Call stopF will be triggered and it will stop Application.OnTime properly.
  • if I want to close the workbook via code then I do not rely on the Workbook_BeforeClose function (because it doesn't work for this somehow) but I call my new closeWorkbook() function when needed, which does terminate Application.OnTime and then closes the workbook.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM