本文介绍了如何启用事件,以便调用Workbook_BeforeSave的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

保存前未调用我的Workbook_BeforeSave事件

这是我的代码:

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

这可能是正常的,因为可能未启用事件.现在,我尝试将Application.Events = True这样放置:

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

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

这不会改变任何内容,保存时仍不会调用Workbook_BeforeSave.但是,当我关闭excel文件时,显示以下错误消息:

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 :

英语翻译为编译错误:过程外的错误指令".

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

显然Application.Events = True不在正确的位置,但是我应该放在哪里?

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

推荐答案

希望这些会有所帮助:

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

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

Application.EnableEvents = True不能插入过程或函数外部.

Application.EnableEvents = True can not be inserted outside procedure or function.

默认情况下启用事件.因此,在vba项目中必须存在某个地方,事件已被禁用.可以通过以下方式搜索:

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

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

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.

您可以使用一个小的子项来更改和查看Application.EnableEvents状态(开/关).将接头放在任何标准模块下.请参见下图.

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.

这篇关于如何启用事件,以便调用Workbook_BeforeSave的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 17:37