Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run-time error when canceling a 'Save As' dialog displayed via VBA

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.

like image 746
David Gard Avatar asked Mar 14 '13 10:03

David Gard


2 Answers

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
like image 93
Kazimierz Jawor Avatar answered Oct 20 '22 11:10

Kazimierz Jawor


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
like image 29
brettdj Avatar answered Oct 20 '22 12:10

brettdj