I need to write a macro in Excel VBA, that terminates a process running in windows tasks AFTER the excel has been closed down. I tried it doing this on event workbook_BeforeClose
Private Sub Workbook_BeforeClose(CANCEL As Boolean)
Run "MacroCloseProcess"
End Sub
Where as MacroCloseProcess is defined like this
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
This works, BUT, if there are changes made in the workbook, excel gives the user option to "Do you want to save the changes you made to 'Sheet1.xlsx' ? Save, Don't Save, Cancel
If user clicks cancel, Excel does not exit ( as per design) but oh, the process has been terminated because it was in a "BeforeClose" event. How can i write this code so that it hits after the excel closes ?
Some of the other ideas are ok and I agree with saving first, but you should ask for their permission beforehand. This also allows the user to save first as it checks first if it's saved.
You should invoke the user to save the workbook before you terminate. E.g.
Take control of the user decision. This is simple code which could be improved if needed.
*EDIT * Better and more elegant option:
Maybe you could offer the user a do you wish to save option before you close the excel and then suppress any further dialogs for the user by
Application.DisplayAlerts=False
orThisWorkbook.Close (False)