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
How to enable events so Workbook_BeforeSave gets called
提问by Jabberwocky
My Workbook_BeforeSave
event 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 = True
like 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文件时,会显示以下错误消息:
The english translation is "Compilation error: Incorrect instruction outside of a procedure."
英文翻译是“编译错误:程序外指令不正确”。
Apparently the Application.Events = True
is not at the right place, but where should I put it ?
显然Application.Events = True
不是在正确的地方,但我应该把它放在哪里?
回答by ZAT
Hope these will help:
希望这些会有所帮助:
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
must be insideThisWorkbook
in a VBA project.Application.EnableEvents = True
can not be inserted outside procedure or function.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.
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.
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
必须ThisWorkbook
在 VBA 项目中。Application.EnableEvents = True
不能插入到程序或函数之外。默认情况下启用事件。因此,vba 项目中一定有某个地方事件被禁用了。这可以通过以下方式搜索:
进入 VBA 项目后,按 Ctrl+F 打开“查找”对话框。然后在当前项目中搜索application.enableevents。按查找下一个。见下图。
您可以使用一个小子来更改和查看 Application.EnableEvents 状态(开/关)。将 sub 放置在任何标准模块下。见下图。