在VBA中写入macros – excel用户closuresExcel之后

我需要在Excel VBA中编写一个macros,在excelclosures后终止在Windows任务中运行的进程。 我试着这样做事件workbook_BeforeClose

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不会退出(按devise),但是,该进程已被终止,因为它在“BeforeClose”事件中。 我怎样才能写这个代码,以便它在Excelclosures后打?

掌握用户的决定。 这是简单的代码,如果需要可以改进。

 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 

* 编辑*更好,更优雅的select:

 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 

其他的一些想法是可以的,我同意先保存,但你应该事先征求他们的许可。 这也允许用户首先检查是否保存。

您应该调用用户在终止之前保存工作簿。 例如

 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 

也许你可以提供给用户一个你想保存的选项,然后closuresExcel,然后禁止用户的任何进一步的对话框

Application.DisplayAlerts=False

ThisWorkbook.Close (False)