Question

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

However, sometimes the document is not already saved, and in some cases I don't want to save it. Unfortunately, clicking 'Cancel' when the 'Save As' dialogue is displayed is causing a run-time error (4198) -

Command failed

Does anyone know how I can prevent this from happening? Thanks.

Was it helpful?

Solution 2

Updated: Now

1. Tests if the file has been previously saved or not
2. If the fileis unsaved, a controlled process is used to show the SaveAs dialog to either save the file, or handle the 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

OTHER TIPS

Please 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

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();
        }

The result will store which button is pressed (0- cancel, 1- ok, 2- close)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top