Existing solutions for similar questions don't work for me.
I need to close the Word application without saving the document. So if a document is open and the user closes the word application DocumentBeforeClose event is fired.
This is the existing code
Private Sub OnDocumentBeforeClose(ByVal doc As Microsoft.Office.Interop.Word.Document, ByRef Cancel As Boolean)
'Some code
End Sub
1st I tried to close the application
Private Sub OnDocumentBeforeClose(ByVal doc As Microsoft.Office.Interop.Word.Document, ByRef Cancel As Boolean)
'Some code
doc.Close() 'This closed the open document but the application remained open, the user had the click X twice to close the application
doc.Close(SaveChanged:= False) 'then I tried this but same result as above
_application.DisplayAlerts = Microsoft.Office.Interop.Word.WdAlertLevel.wdAlertsNone ' Did nothing
End Sub
I cannot just Quit() the application in the DocumentBeforeClose event handler because in the application when the user switches the document (from a list of documents) the current open document needs to be closed before opening the next document. So if a user is trying to switch document then DocumentBeforeClose event is fired therefore I cannot implement Quit() here.
2nd I tried this
Private Sub OnDocumentBeforeClose(ByVal doc As Microsoft.Office.Interop.Word.Document, ByRef Cancel As Boolean)
'Some code
_application.ActiveDocument.Saved = True
_application.ActiveDocument.SaveNormalPrompt = False
End Sub
3rd I tried this
AddHandler _application.DocumentBeforeSave, AddressOf OnBeforeSave
Private Sub OnDocumentBeforeClose(ByVal doc As Microsoft.Office.Interop.Word.Document, ByRef Cancel As Boolean)
'Some code
If Not Doc.Saved Then
Doc.SaveAs2()
End If
End Sub
Private Sub OnBeforeSave(ByVal doc As Microsoft.Office.Interop.Word.Document, ByRef SaveAsUI As Boolean, ByRef Cancel As Boolean)
SaveAsUI = False 'Saves the document without showing Save dialog
Cancel = True 'then I tried Cancel, shows the Save dialog. Then tried both SaveAsUI and Cancel but did not help
End Sub
I have spent days and now I desperately need a solution for this. Can someone please help with this?
The following code works like a charm on my machine and I don't get any dialogs for saving the changed document when Word is being closed: