Excel VBA 如何防止用户在 msoFileDialogSaveAs 中点击取消

Excel VBA How to prevent user from hitting cancel in msoFileDialogSaveAs

我是 VBA 的新手,我正在为我的老板创建一个模板。我想强制用户 "save as" 这样他们就不会覆盖模板。换句话说,我想禁用弹出另存为对话框时的取消按钮。

这是我的代码:

Dim fPth As Object
Set fPth = Application.FileDialog(msoFileDialogSaveAs)

With fPth
    .InitialFileName = CTAPath
    .InitialFileName = CTAName & "_CAP DATA"
    .Title = "Save with your CTA file"
    .InitialView = msoFileDialogViewList
    .FilterIndex = 2
    If .Show = -1 Then
        .Execute

    End If
End With

我想我应该在 IF 语句中创建一个 ELSE 语句,但我不知道应该是什么。我试过搜索,但没有找到任何解决方案。

谢谢!

我不确定您能否禁用 Cancel 按钮,但有解决方法...

您可以循环 .Show 方法直到用户点击 Save 按钮 ;)

例如:

Sub PreventCancel()

Dim fPth As Object
Set fPth = Application.FileDialog(msoFileDialogSaveAs)
Dim result As Variant

With fPth
    .InitialFileName = CTAPath
    .InitialFileName = CTAName & "_CAP DATA"
    .Title = "Save with your CTA file"
    .InitialView = msoFileDialogViewList
    .FilterIndex = 2
    Do
        result = .Show
    Loop While result <> True
   .Execute
End With

End Sub

[编辑]

我建议使用 Application.GetSaveAsFilename Method (Excel) 而不是 FileDialog,因为它可以让您更好地控制它。

请同时阅读对您的问题的宝贵评论。

这不是这样做的方法:如果用户在 "Save as" 文件列表中选择文件本身,您可能会遇到同样的情况。
我建议您将该文件设置为只读,这样任何人都无法更改或覆盖它。