2013-04-11 138 views
4

我需要在Excel VBA中編寫一個宏,該宏在Excel關閉後終止在Windows任務中運行的進程。我試了一下這樣的事件workbook_BeforeClose在VBA中寫宏 - excel在用戶關閉Excel之後

Private Sub Workbook_BeforeClose(CANCEL As Boolean) 
    Run "MacroCloseProcess" 
End Sub 

凡爲MacroCloseProcess是這樣

Private Sub MacroCloseProcess() 
    Dim oWMT As Object, oProcess As Object 
    Set oWMT = GetObject("winmgmts://") 
    For Each oProcess In oWMT.InstancesOf("Win32_Process") 
     If (oProcess.name) = pWcfHostApp Then 

      If oProcess.Terminate() = 0 Then Exit Sub 
     End If 
    Next 
End Sub 

這工作定義,但是,如果在工作簿中所做的更改,Excel將用戶選項 「你想保存你對'Sheet1.xlsx'所做的修改嗎?保存,不保存,取消

如果用戶單擊取消,Excel不會退出(按設計)但是,過程已經因爲它在「BeforeClose」事件中被終止我可以寫這個代碼,以便它在Excel關閉後命中嗎?

回答

5

的採取控制抑制了用戶的任何進一步的對話框中的用戶用戶決定。這是簡單的代碼,如果需要可以改進。

Private Sub Workbook_BeforeClose(Cancel As Boolean) 
'take control of what user can do: 
If MsgBox("Do you want to save and exit?", vbYesNo) = vbYes Then 
    Application.DisplayAlerts = False 
     ThisWorkbook.Save 
     'call your MacroCloseProcess here 
    Application.DisplayAlerts = True 
Else 
    Cancel = True 
End If 
End Sub 

* 編輯*更好,更優雅的選擇:

Private Sub Workbook_BeforeClose(Cancel As Boolean) 
'take control of what user can do: 
    Application.DisplayAlerts = False 
    Dim filePath As Variant 

    If Len(ThisWorkbook.Path) > 0 Then 
     'has been already saved therefore just ask 
     'this would be rarely meet, only whan call for the first time 
     'or if this solution was placed in class module for all doc 

     If MsgBox("Do you want to save and exit?", vbYesNo) = vbYes Then 
      ThisWorkbook.Save 
      'call your MacroCloseProcess here 
      MsgBox "exit" '<-- to remove, kept for tests 
     Else 
      Cancel = True 
     End If 
    Else 
     'document was not saved before- show standard file dialog 

     filePath = Application.GetSaveAsFilename() 
     If VarType(filePath) = vbString Then 

      ActiveWorkbook.SaveAs Filename:=filePath 
      'call your MacroCloseProcess here 
      MsgBox "exit" '<-- to remove, kept for tests 

     Else 
      Cancel = True 
     End If 
    End If 
    Application.DisplayAlerts = True 
End Sub 
0

也許你可以提供你希望你關閉Excel之前保存選項,然後通過

Application.DisplayAlerts=False

ThisWorkbook.Close (False)

5

一些其他的想法是好的,我同意節約優先,但你應該問他們的准許。這也允許用戶首先檢查是否保存。

您應該在終止之前調用用戶保存工作簿。例如。

Private Sub Workbook_BeforeClose(CANCEL As Boolean) 

If Not Me.Saved Then 
    Msg = "Do you want to save the changes you made to " 
    Msg = Msg & Me.Name & "?" 
    Ans = MsgBox(Msg, vbQuestion + vbYesNoCancel) 
    Select Case Ans 
     Case vbYes 
      Me.Save 
     Case vbNo 
      Me.Saved = True 
     Case vbCancel 
      Cancel = True 
      Exit Sub 
    End Select 
End If 

Run "MacroCloseProcess" 

End sub