我希望我的WB在不活动时间之后触发一些代码(由我自然设置)。我只能在不活动时间之后找到关闭WB的代码,但我希望代码能够做其他事情,不同于关闭WB。我找到了关闭WB的代码:
本工作簿模块:
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做的事件,在不活动之后,而不是关闭WB?
答案 0 :(得分:2)
您需要在常规模块中进行更改。
您必须指定包含您要执行的任何内容的过程的名称,而不是在close_wb()
函数调用中传递字符串Application.OnTime
。
以下是帮助您入门的代码:
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
方法的详细信息,请查看here。
编辑:经过一些测试后,您似乎无法在stop_Countdown()
子程序中调用Workbook_BeforeClose
:它会抛出错误。根据{{3}},在 工作簿模块 中,您必须将过程Workbook_BeforeClose
替换为以下过程:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Close_WB
End Sub
并添加以下程序:
Public Sub Close_WB()
stop_CountDown
ThisWorkbook.Close SaveChanges:=True
End Sub