Runtime error when canceling the Save As dialog box displayed via VBA

I have a macro that formats a document in a specific way and then saves it using ActiveDocument.Save .

However, sometimes the document has not yet been saved, and in some cases I do not want to save it. Unfortunately, clicking Cancel when the Save As dialog is displayed causes a runtime error (4198) -

Failed to execute command

Does anyone know how I can prevent this? Thanks.

+6
source share
3 answers

Updated: now

1. Checks if the file was previously saved or not. 2. If the file is not saved, a managed process is used to display the SaveAs dialog, either save the file or process Cancel

code

 Dim bSave As Boolean If ActiveDocument.Path = vbNullString Then bSave = Application.Dialogs(wdDialogFileSaveAs).Show If Not bSave Then MsgBox "User cancelled", vbCritical Else ActiveDocument.Save End If 
+2
source

Try the following by adding some error handling instructions:

 On Error Resume Next 'to omit error when cancel is pressed ActiveDocument.Save If Err.Number <> 0 Then 'optional, to confirmed that is not saved MsgBox "Not saved" End If On Error GoTo 0 'to return standard error operation 
+3
source

for vsto developers please go here

  if (Globals.ThisAddIn.Application.ActiveDocument.Path == String.Empty) { Word.Dialog dlg; Object timeout = 3000; dlg = Globals.ThisAddIn.Application.Dialogs[ Word.WdWordDialog.wdDialogFileSaveAs]; int result = dlg.Display(ref timeout); } else { Globals.ThisAddIn.Application.ActiveDocument.Save(); } 

As a result, the button pressed will be saved (0 - cancel, 1- ok, 2- close)

0
source

All Articles