vba 如何启用事件以便 Workbook_BeforeSave 被调用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26296597/
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-12 04:48:27  来源:igfitidea点击:

How to enable events so Workbook_BeforeSave gets called

excel-vbavbaexcel

提问by Jabberwocky

My Workbook_BeforeSaveevent is not called before saving

Workbook_BeforeSave保存前未调用我的事件

This is my code:

这是我的代码:

Option Explicit

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
   a = MsgBox("Do you really want to save the workbook?", vbYesNo)
   If a = vbNo Then Cancel = True
End Sub

This is probably normal, because events are probably not enabled. Now I tried to put Application.Events = Truelike this:

这可能是正常的,因为事件可能未启用。现在我试着Application.Events = True这样写:

Option Explicit
Application.Events = True

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
   a = MsgBox("Do you really want to save the workbook?", vbYesNo)
   If a = vbNo Then Cancel = True
End Sub

This doesn't change anything, Workbook_BeforeSave is still not called up on saving. But when I close the excel file, following error message is displayed :

这不会改变任何东西,Workbook_BeforeSave 在保存时仍然没有被调用。但是当我关闭excel文件时,会显示以下错误消息:

enter image description here

在此处输入图片说明

The english translation is "Compilation error: Incorrect instruction outside of a procedure."

英文翻译是“编译错误:程序外指令不正确”。

Apparently the Application.Events = Trueis not at the right place, but where should I put it ?

显然Application.Events = True不是在正确的地方,但我应该把它放在哪里?

回答by ZAT

Hope these will help:

希望这些会有所帮助:

  1. Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)must be inside ThisWorkbookin a VBA project.

  2. Application.EnableEvents = Truecan not be inserted outside procedure or function.

  3. Events are enabled by default. So, there must be somewhere inside vba project Events are getting disabled. This can be searched by :

    Once you are inside VBA project, Press Ctrl+F to open the Find dialog box. Then search for application.enableevents in the current project. Press Find Next. See the image below.

  4. You can use a little sub to change and view the Application.EnableEvents status (ON/OFF). Place the sub under any standard module. See the image below.

  1. Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)必须ThisWorkbook在 VBA 项目中。

  2. Application.EnableEvents = True不能插入到程序或函数之外。

  3. 默认情况下启用事件。因此,vba 项目中一定有某个地方事件被禁用了。这可以通过以下方式搜索:

    进入 VBA 项目后,按 Ctrl+F 打开“查找”对话框。然后在当前项目中搜索application.enableevents。按查找下一个。见下图。

  4. 您可以使用一个小子来更改和查看 Application.EnableEvents 状态(开/关)。将 sub 放置在任何标准模块下。见下图。

enter image description here

在此处输入图片说明