简体   繁体   English

保护VBA Excel免受他人保存

[英]Protect VBA Excel from saving by others

I am trying to protect my Excel VBA from saving by others who are also using my macro. 我试图保护我的Excel VBA,防止其他人也在使用我的宏进行保存。 I tried using the below code but it is not working. 我尝试使用以下代码,但无法正常工作。 I want to prevent others from saving the VBA Excel before closing as well as while using Ctrl + S for saving. 我想防止其他人在关闭之前以及使用Ctrl + S进行保存时保存VBA Excel。

Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
    If Not SaveAsUI Then
        Cancel = True
        MsgBox "You cannot save this workbook"
    End If
End Sub

I'm using Excel 2019 and I cannot reproduce your issue. 我正在使用Excel 2019,但无法重现您的问题。 The code works as expected. 该代码按预期工作。 If I press Save I get the message box and it does not save. 如果按“ 保存 ”,则会显示消息框,但不会保存。 If I close the workbook, it asks me if I want to save, if I press Save I again get the message box and it does not save. 如果我关闭工作簿,它会询问我是否要保存,如果按“ 保存”,我会再次收到消息框,但它不保存。

But you can try to add a Workbook_BeforeClose event with a ThisWorkbook.Saved = True to make VBA believe the workbook was already saved. 但是您可以尝试使用ThisWorkbook.Saved = True添加Workbook_BeforeClose事件,以使VBA相信该工作簿已被保存。 This prevents the message box when closing the workbook, that asks if you want to save or not. 这样可以避免在关闭工作簿时询问您是否要保存的消息框。

Option Explicit

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    ThisWorkbook.Saved = True
End Sub

Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
    If Not SaveAsUI Then
        Cancel = True
        MsgBox "You cannot save this workbook"
    End If
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM