application.ontime not cancelling or running in background

蹲街弑〆低调 提交于 2021-01-28 01:34:10

问题


I'm using the Application.Ontime command to automatically close a spreadsheet after a period of inactivity (10 minutes).

The following code seems to work in general, however, it appears that if you manually close the sheet yourself, the workbook still seems to be active in the background and at the last designated 'endtime' will open itself so that it can close itself.

This is also evident in the VBA code window as after the CloseWB macro runs and the excel workbook appears to be closed, it is still listed in the VBA project explorer window.

Sub RunTime()
Static EndTime
If Not EndTime = "" Then ActiveWorkbook.Application.OnTime EndTime, "CloseWB", , False
EndTime = Now + TimeValue("00:10:00")
ActiveWorkbook.Application.OnTime EndTime, "CloseWB", , True
End Sub

Sub CloseWB()

    Application.DisplayAlerts = False
    With ThisWorkbook
        .Save
        .Close
    End With
End Sub

I don't want to completely shutdown excel (application.quit) in case users have other workbooks open but need to try and stop the specific workbook running in the background.

Any ideas?


回答1:


You need to stop the timer. Declare EndTime as a public variable, then turn the timer off in the Workbook_BeforeClose event.

Option Explicit

Public EndTime As Variant

Sub RunTime()
If Not EndTime = "" Then ActiveWorkbook.Application.OnTime EndTime, "CloseWB", , False
EndTime = Now + TimeValue("00:10:00")
ActiveWorkbook.Application.OnTime EndTime, "CloseWB", , True
End Sub

Sub CloseWB()

    Application.DisplayAlerts = False
    With ThisWorkbook
        .Save
        .Close
    End With
End Sub

In the Workbook object:

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    On Error Resume Next
    Application.OnTime earliesttime:=EndTime, procedure:="CloseWB", schedule:=False
End Sub


来源:https://stackoverflow.com/questions/50273166/application-ontime-not-cancelling-or-running-in-background

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!