我需要在 Excel VBA 中编写一个宏,该宏在 Excel 关闭后终止在 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 不会退出(根据设计),但是哦,该进程已终止,因为它处于“BeforeClose”事件中。我怎样才能编写这段代码,以便它在 Excel 关闭后命中?
最佳答案
控制用户决策。这是简单的代码,可以根据需要进行改进。
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
关于vba - 在用户关闭 Excel 后,在 VBA - excel 中编写宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15947082/