2011-01-20 90 views
0

不久前,我掀起(或發現)一些代碼,以便在用戶將其打開(例如過夜或全天)後的一段時間後自動關閉共享工作簿。代碼運行良好,除了關閉其駐留的工作簿時;它也關閉所有的工作簿,並且也是優秀的(沒有Application.Quit)。用戶對此感到厭煩,有誰知道我怎麼才能讓它只能關閉(Thisworkbook),而不是所有其他的?Excel - 關閉工作簿的計時器

感謝。下面

代碼:

Option Explicit 

' Declarations 
Private Declare Function SetTimer Lib "user32" (ByVal hwnd As Long, ByVal nIDEvent As Long, ByVal uElapse As Long, ByVal lpTimerFunc As Long) As Long 
Private Declare Function KillTimer Lib "user32" (ByVal hwnd As Long, ByVal nIDEvent As Long) As Long 
Private mlngTimerID As Long 

' start the timer 
Public Sub StartTimer(lngInterval As Long) 
    mlngTimerID = SetTimer(0, 0, lngInterval, AddressOf TimerCallBack) 
End Sub 

' when the timer goes off 
Public Sub TimerCallBack(ByVal hwnd As Long, ByVal uMsg As Long, ByVal idEvent As Long, ByVal dwTime As Long) 

' stop the timer 
StopTimer 

    ' don't save if read only 
If ThisWorkbook.ReadOnly = False Then 

    ' save 
    ThisWorkbook.Save 

End If 

' exit without saving 
ThisWorkbook.Activate 
ThisWorkbook.Close False 

End Sub 

Public Sub StopTimer() 
    KillTimer 0, mlngTimerID 
End Sub 

'To use timer: 
'To start the timer 
'Call startTimer(1000)'1000 = 1 Second 
'To stop timer 
'Call stopTimer 

回答

1

我知道這是一個老問題,但我想我會分享,對我的工作的決議。打開時,工作簿將存儲爲公用變量,以便在計時器到期時關閉該工作簿。如果工作簿在時間到期之前關閉,則取消定時器。如果計時器到期並且工作簿仍處於打開狀態,則會自動保存並關閉。

插入下面的代碼爲 「的ThisWorkbook」 的

'When the workbook is opened, call StartTimer() 
Public Sub Workbook_Open() 
    Run "StartTimer" 
End Sub 

'Detect if the workbook is closed 
Public Sub Workbook_BeforeClose(Cancel As Boolean) 
    'Cancel Saveclose 
    Run "StopTimer" 
End Sub 

代碼插入到一個模塊

'Global variables 
Public RunWhen As Double 
Public Const cRunIntervalSeconds = 300 ' seconds (set to 5 minutes) 
Public Const cRunWhat = "SaveClose" ' the name of the procedure to run 
Public GlobalBook As Workbook 

'Start Timer using interval set in global variables 
Sub StartTimer() 
    Set GlobalBook = ActiveWorkbook 
    RunWhen = Now + TimeSerial(0, 0, cRunIntervalSeconds) 
    Application.OnTime EarliestTime:=RunWhen, Procedure:=cRunWhat, _ 
     Schedule:=True 
End Sub 

'Stop the Timer whenever the workbook is closed prematurely 
Public Sub StopTimer() 
    On Error Resume Next 
    Application.OnTime EarliestTime:=RunWhen, Procedure:=cRunWhat, _ 
     Schedule:=False 
End Sub 

'Close the workbook automatically once the Timer has expired 
Public Sub SaveClose() 
    'Time is up, workbook will save and close automatically 
    Dim wb As Workbook 
    For Each wb In Workbooks 
     'Check to see if workbook is still open 
     If wb.Name = GlobalBook.Name Then 
      Set wb = Application.Workbooks(GlobalBook.Name) 
      'Close workbook and Save Changes 
      wb.Close SaveChanges:=True 
     End If 
     Next 
End Sub 
相關問題