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_BeforeClos
Take control of the user decision. This is simple code which could be improved if needed.
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
*EDIT * Better and more elegant option:
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