5

Error Message

        If IsWorkbookOpen("CONTRACT\CONTRACTLIST_Cement.xlsx") Then
            x = 0
        Else
            Application.DisplayAlerts = False
            ActiveWorkbook.Close savechanges:=True
            Application.DisplayAlerts = True
        End If

Hi, despite using the above code, the save as prompt still occasionally appears and affect the program. Does anyone know how to stop it completely? The problem is that after I click save as, it will alert me that it was still open.

enter image description here

4

2 回答 2

9

试试下面的代码

明确地参考工作簿而不是ActiveWorkbook

Sub test()
   If IsWorkbookOpen("CONTRACT\CONTRACTLIST_Cement.xlsx") Then
            x = 0
    Else
        Application.DisplayAlerts = False
        ThisWorkbook.Save
        ThisWorkbook.Close False
        Application.DisplayAlerts = True
    End If

End Sub
于 2013-07-16T11:43:37.603 回答
5

您可以Workbook_BeforeSave在对象中使用 EventThisWorkbook来捕获用户选择 SaveAs(或使用键盘快捷键),这将导致显示 Save As 提示并将SaveAsUI其设置为 true。如果SaveAsUI为真,这意味着用户正在尝试将文件另存为其他内容,因此您可以取消另存为操作。

打开 Visual Basic 窗口 (Alt + F11) 并将以下代码放入ThisWorkbook.

禁用另存为

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)

    If (SaveAsUI = True) Then
        MsgBox "Sorry. I can't have you saving this file as something else."
        Cancel = True
    End If
End Sub

您可以根据需要删除该MsgBox行;如果您想通知用户该功能已禁用,我将其作为示例

要同时禁用Save 和 Save As 功能,您将删除该if语句并取消 Save 操作,无论是否显示 Save as 提示。

禁用保存和另存为

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)

    MsgBox "Sorry. I can't have you saving this file at all."
    Cancel = True
End Sub

如果您只想禁用 Save 操作,您只需要查找用户正在保存但未显示 SaveAsUI 的位置即用户只是保存文件)。

禁用保存

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)

    If (SaveAsUI = False) Then
        MsgBox "Sorry. I can't have you saving any updates to this file."
        Cancel = True
    End If
End Sub

最后,请注意,如果用户只是关闭文件,用户仍会收到保存提示。用户将无法保存并且文件将关闭,但如果您希望体验更简洁,则需要进行额外的更改。当用户关闭文件时,Excel 会检查ThisWorkbook.Saved变量以查看文件是否已保存。如果为 false,则会提示用户保存文件。为了防止这种情况,我们可以将此布尔值设置为 true 而不保存,从而“欺骗”Excel 认为文件已保存

禁用保存和另存为,包括在用户尝试关闭文件之后

在您的代码后添加以下Workbook_BeforeSave代码。

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    ActiveWorkbook.Saved = True
    MsgBox "Click OK to continue closing this file. Changes will not be saved."
End Sub
于 2013-07-16T12:25:54.387 回答