不活动后触发代码
我希望我的WB在闲置时间之后触发一些代码(自然而然地由我设置)。 我只能find代码来closures静止时间后的WB,但我希望代码做一些其他的事情,不同于closuresWB。 我发现这个closuresWB的代码:
此工作簿模块:
Private Sub Workbook_BeforeClose(Cancel As Boolean) stop_Countdown ThisWorkbook.Save End Sub Private Sub Workbook_Open() start_Countdown End Sub Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range) stop_Countdown start_Countdown End Sub Private Sub Workbook_SheetCalculate(ByVal Sh As Object) stop_Countdown start_Countdown End Sub Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, _ ByVal Target As Excel.Range) stop_Countdown start_Countdown End Sub
常规模块:
Option Explicit Public Close_Time As Date Sub start_Countdown() Close_Time = Now() + TimeValue("00:00:10") Application.OnTime Close_Time, "close_WB" End Sub Sub stop_Countdown() Application.OnTime Close_Time, "close_WB", , False End Sub Sub close_wb() ThisWorkbook.Close True End Sub
在代码的哪一部分,我应该介绍一下在WB处于不活动状态之后我想要做的事情,而不是closuresWB?
您需要在常规模块中进行更改。
而不是在你的Application.OnTime
函数调用中传递stringclose_wb()
,你必须指定包含任何你想要执行的过程的名字。
这里是开始的代码:
Option Explicit Public Inactivity_Time As Date Sub start_Countdown() Inactivity_Time = Now() + TimeValue("00:00:10") Application.OnTime Inactivity_Time, "my_procedure" ' <- Notice that I changed the name of the procedure here End Sub Sub stop_Countdown() On Error Resume Next Application.OnTime Inactivity_Time, "my_procedure", , False ' <- And here too. On Error GoTo 0 End Sub Sub my_procedure() ' The code to perform you event goes here End Sub
请在这里查看有关Application.OnTime
方法的更多详细信息。
编辑:经过一些testing,似乎无法在Workbook_BeforeClose
子过程中调用stop_Countdown()
:它会引发错误。 根据这篇文章 ,在您的工作簿模块中 ,您必须将Workbook_BeforeClose
过程replace为以下一个:
Private Sub Workbook_BeforeClose(Cancel As Boolean) Close_WB End Sub
并添加以下步骤:
Public Sub Close_WB() stop_CountDown ThisWorkbook.Close SaveChanges:=True End Sub