Excel VBA只读取代BeforeSave

时间:2019-02-20 21:48:40

标签: excel vba before-save

我有包含用于保存文档的业务逻辑的代码(Excel 365),以确保正确的命名约定,文件位置等作为Sub Workbook_BeforeSave

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Cancel = True  ''Cancels the Save from the button push or Ctrl+S
Application.EnableEvents = False
'' code code code
Application.EnableEvents = True
End Sub

问题在于,如果文件以只读方式打开(大多数情况下会打开),Excel将提示“文件为只读”(图a),然后转到文件功能区中的“另存为”屏幕(图b)。在按下“保存”按钮之前,Workbook_BeforeSave子项不会起作用。即使子程序运行后,它也不会移出该屏幕。 有什么办法可以做到:

  1. 进入“只读”提示...或
  2. 编写一些代码以移出“另存为”屏幕吗?

MS Read-Only promt(图a) Save As Screen(图b)

非常感谢!

1 个答案:

答案 0 :(得分:1)

这不是一个完美的方法,请尝试一下。 即使按下“保存”按钮,这也将完全取消保存,您可以添加自己的保存代码。

编辑:刚刚意识到下面的代码不会停止只读警报,但是当您单击“保存”时,它将取消“保存”并关闭“另存为”菜单。但是,当他们使用Ctrl + S时,发送键{ESC}会触发Ctrl + ESC,从而打开“星空菜单” ...

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
    'Disable Read Only Alert
    Application.DisplayAlerts = False
    'Disable Events
    Application.EnableEvents = False
    'Cancel Save
    Cancel = True
    'Do whatever code you need in here
    '
    'Mark Workbook as Saved, allowing for the file to close without an alert even if not saved
    ThisWorkbook.Saved = True
    'Send Escape Key to leave Save As Menu
    Application.SendKeys "{ESC}", 1
    'Enable Events
    Application.EnableEvents = True
    'Enable Alerts
    Application.DisplayAlerts = True
End Sub