不活动后关闭Excel,即使在编辑模式下也是如此

时间:2014-03-17 16:38:37

标签: excel vba excel-vba idle-timer

我不确定这是否可能当我在网上搜索答案时我没有找到任何结果。我有一个宏,它将在5分钟不活动后关闭。像魅力一样工作,除非用户正在编辑单元格时计时器没有启动,因此它不会因此而关闭。有没有办法让excel有一个计时器,用户处于编辑模式多长时间,然后它将把它们从中取出。一旦退出编辑模式,宏将开始5分钟不活动。非常感谢任何帮助!

这是工作簿模块

Private Sub Workbook_BeforeClose(Cancel As Boolean)
Me.Saved = True
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

这是标准模块

Option Explicit
Public Close_Time As Date
Sub start_Countdown()
    Close_Time = Now() + TimeValue("00:05:00")
    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

2 个答案:

答案 0 :(得分:2)

您需要某种过程监视器/任务终结器在VBA之外来执行此操作,因为VBA已被锁定"当用户处于输入模式时。

答案 1 :(得分:1)

你可以试试这个:

Public Declare Function SetTimer Lib "user32" ( _
 ByVal HWnd As Long, _
 ByVal nIDEvent As Long, _
 ByVal uElapse As Long, _
 ByVal lpTimerFunc As Long) As Long

Public Declare Function KillTimer Lib "user32" ( _
 ByVal HWnd As Long, _
 ByVal nIDEvent As Long) As Long

Public TimerID As Long
Public TimerSeconds As Single

Sub StartTimer()
  TimerSeconds = 5*60 ' how often to "pop" the timer (5 minutes in the example).
  TimerID = SetTimer(0&, 0&, TimerSeconds * 1000&, AddressOf TimerProc)
End Sub

Sub EndTimer()
 On Error Resume Next
 KillTimer 0&, TimerID
End Sub

Sub TimerProc(ByVal HWnd As Long, ByVal uMsg As Long, _
    ByVal nIDEvent As Long, ByVal dwTimer As Long)

 ' call here whatever you want to call
End Sub

即使在编辑模式下也一直有效,不要忘记在退出前调用StartTimer启动和EndTimer ...