Write a Macro in VBA - excel AFTER the user has closed the Excel

前端 未结 3 1885
闹比i
闹比i 2021-02-10 02:20

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

3条回答
  •  情深已故
    2021-02-10 02:42

    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
    

提交回复
热议问题