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

落爺英雄遲暮 提交于 2019-12-03 08:18:45

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
glh

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.

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

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 or

ThisWorkbook.Close (False)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!