取消通过 VBA 显示的“另存为”对话框时出现运行时错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15407281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 20:02:54  来源:igfitidea点击:

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

vbasaveword-2007

提问by David Gard

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

我有一个宏,它以某种方式格式化文档,然后使用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) -

但是,有时文档尚未保存,在某些情况下我不想保存它。不幸的是,在显示“另存为”对话框时单击“取消”会导致运行时错误 (4198) -

Command failed

命令失败

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

有谁知道我如何防止这种情况发生?谢谢。

采纳答案by brettdj

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 SaveAsdialog to either save the file, or handle the Cancel

1. 测试文件先前是否已保存
2. 如果文件未保存,则使用受控过程显示SaveAs对话框以保存文件或处理文件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

回答by Kazimierz Jawor

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

回答by Gomes

for vsto developers, please go here

对于 vsto 开发者,请到这里

    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)

结果将存储按下了哪个按钮(0-取消,1-确定,2-关闭)