Word VBA(Events)

Word Events

在Word中只有Application object和Document object响应事件:

Events With Applicationobject :

NewDocument,  DocumentOpen,

DocumentBeforeClose, DocumentBeforePrint, DocumentBeforeSave

WindowActivate, WindowDeactivate, WindowSelectionChange, WindowBeforeDoubleClock,  WindowBeforeRightClick, Quit

Events With Document object:

New, Open, Close 

此 外,在Document上的ActiveX Cobtrols也响应事件。     对每一FormField可以指定On Entry和On Exit 宏,相当于 GotFocus和LostFocus事件过程。当然在Word VB Project中建立的UserForms及其上的Controls 也响应事件。  

 

Events: When you open adocument 

当Open MyDoc1.doc文档时,发生以下事件:

   1. Document_Open

   2. App_DocumentChange :

   3. App_DocumentOpen :       C:\…\MyDoc1.doc 

 如果Order4.Doc有AttachedTemplate,则当Open该Doc时,发生以下事件:    1. Template’s Document_Open(Doc打开也触发模板的Open事件。)

   2. App_DocumentChange (如果这不是第一个打开的文档,发生App_DocumentChange事件)    3. Document’s Document_Open

   4. App_DocumentOpen :       C:\My Documents\Order4.doc

 

Events: When you close adocument

 当Close文档时,发生以下事件:

   1.App_DocumentBeforeClose:C:\…\MyDoc1.doc   2. Document_Close

   3. 对话框SaveChanges ?

   4. 如果Save, App_DocumentBeforeSave :C:\…\MyDoc1.doc       (如果不Save changes则不发生App_DocumentBeforeSave。)

 如果Order4.Doc有AttachedTemplate,则当Close该Doc时,发生以下事件:    1. App_DocumentBeforeClose:C:\MyDocuments\Order4.doc

   2. Template’s Document_Close (Doc关闭也触发模板的Close事件。)   3. Document’s Document_Close

   4. 对话框SaveChanges  to .Doc ?  

   5. Yes:  App_DocumentBeforeSave: C:\MyDocuments\Order4.doc    6. 对话框SaveChanges  to .Dot ?

   7. Yes:App_DocumentBeforeSave: C:\WINDOWS\ApplicationData\Microsoft\Templates\Order.dot    8. 关闭Word文档窗口

   注:如果你不希望Save模板(即使有Changes),可以在最后一个App_DocumentBeforeSave事件

之前,例如在Template’s Document_Close事件里,执行以下语句:

ActiveDocument.AttachedTemplate.Saved = True 

(不要用DocumentBeforeSave事件里的Cancel=True,它不关闭.Doc窗口。) 

 

 

如果你希望在单独打开模板.dot文件(作为通常的Document文件)时仍可以保存对模板的 Changes,可在Template’s Document_Close事件里加上以下语句:

          IfActiveDocument.FullName <> ThisDocument.FullName Then

            ActiveDocument.AttachedTemplate.Saved = True 'if as an attachedtemplate          

End If

因 为在单独打开模板.dot文件时,ActiveDocument.FullName =ThisDocument.FullName。 在模板里写 ThisDocument表示该模板文件,而ActiveDocument可能是指基于该模板的doc文 件,或者模板文件本身(单独打开时)。

(不 管是否单独打开,在模板里ActiveDocument.AttachedTemplate和ThisDocument总是指同一模板, 但在.Doc 里写,它们不同,而且是两种object类型:Template和 Document,虽 然它们有些共同的属性。)

Document和 Template都有属性Saved。如果有Changes,系统自动置它为False。你在Close时 置它为True表示不要Save, Save Changes 对话框也不再出现。注意,DocumentBeforeSave事件发生在Save Changes 对话框且 Yes之后。

如果你不按Close命令,直接按Save命令,Close事件不发生。但App_DocumentBeforeSave 发生。 此时用Cancel=True可以禁止Save,但应先判断Save的是.doc还是dot,事件过程里 有参数给出。(用OS文件属性ReadOnly 最保险。)

 

New事件: Document_New和App_NewDocument

仅在.Dot模板里才可有Document_New事件过程。 在新建基于一模板的的Doc时发生以下事件:

         Template’s Document_New

         App_DocumentChange (如果原来已有某ActiveDocument文档)         

         App_NewDocument :Document1(新文档,无.doc后缀)

Auto Macros

By giving a macro a special name, you can run it automatically when youperform an operation such as starting Word or opening a document. Wordrecognizes the following names as automatic macros, or "auto" macros.

 Macro name     When it runs                                 

 AutoExec       When you start Word or load a globaltemplate      

 AutoNew        Each time you create a newdocument     

 AutoOpen       Each time you open an existingdocument     

 AutoClose      Each time you close a document

 AutoExit       When you quit Word or unload a globaltemplate 

Auto macros in code modules are recognized if either of the followingconditions are true.

l     Themodule is named after the auto macro (for example, AutoExec) and it contains aprocedure named "Main."

l     Aprocedure in any module is named after the auto macro.  

Just like other macros, auto macros can be stored in the Normaltemplate, another template, or a document. In order for an auto macro to run, itmust be either in the Normal template, in the active document, or in thetemplate on which the active document is based. The only exception is theAutoExec macro, which will not run automatically unless it is stored in one ofthe following: the Normal template, a template that is loaded globally throughthe

Templates and Add-Ins dialog box, or a global template stored in thefolder specified as the Startup folder.

In the case of a naming conflict (multiple auto macros with the samename), Word runs the auto macro stored in the closest context. For example, ifyou create an AutoClose macro in a document and the attached template, only theauto macro stored in the document will execute. If you create an AutoNew macroin the normal template, the macro will run if a macro named AutoNew doesn'texist in the document or the attached template.

Note   You can hold down theSHIFT key to prevent auto macros from running. For example, if you create a newdocument based on a template that contains an AutoNew macro, you can preventthe AutoNew macro from running by holding down SHIFT when you click OK in theNew

dialog box (File menu) and continuing to hold down SHIFT until the newdocument is displayed. In a macro that might trigger an auto macro, you can usethe following instruction to prevent auto macros from running:

WordBasic.DisableAutoMacros

 

Using Events with theApplication Object

To create an event handler for an event of the Application object, youneed to complete the following three steps:

l   Declare an object variable in a class moduleto respond to the events.

l   Write the specific event procedures.

l  Initialize thedeclared object from another module. 

Declare the Object Variable

Before you can write procedures for the events of the Applicationobject, you must create a new class module and declare an object of typeApplication with events. For example, assume that a new class module is createdand called EventClassModule. The new class module contains the following code.

Public WithEvents App As Word.Application

Write the Event Procedures

After the new object has been declared with events, it appears in theObject drop-down list box in the class module, and you can write eventprocedures for the new object. (When you select the new object in the Objectbox, the valid events for that object are listed in the Procedure drop-downlist box.) Select an event from the Procedure drop-down list box; an emptyprocedure is added to the class module.

Private Sub App_DocumentChange() 

End Sub

Initializing the Declared Object

Before the procedure will run, you must connect the declared object inthe class module (App in this example) with the Application object. You can dothis with the following code from any module.

Dim X As New EventClassModule Sub Register_Event_Handler()

    Set X.App = Word.ApplicationEnd Sub

Run the Register_Event_Handler procedure. After the procedure is run,the App object in the class module points to the Word Application object, andthe event procedures in the class module will run when the events occur

Using Events with theDocument Object

The Document object supports three events: Close, New and Open. Youwrite procedures to respond to these events in the class module named"ThisDocument." :

1. Under your Normal project or document project in the ProjectExplorer window,

double-click ThisDocument. (In Folder view, ThisDocument is located inthe Microsoft Word Objects folder.)

2. Select Document from the Object drop-down list box. 3. Select anevent from the Procedure drop-down list box.      An empty subroutine is added to the classmodule.

4. Add the Visual Basic instructions you want to run when the eventoccurs. 

The following example shows a New event procedure in the Normal projectthat will run when a new document based on the Normal template is created.

Private Sub Document_New()

    MsgBox "New document wascreated" End Sub

 

The following example shows a Close event procedure in a documentproject that runs only when that document is closed.

Private Sub Document_Close()

    MsgBox "Closing thedocument" End Sub

Unlike auto macros, event procedures in the Normal template don't havea global scope. For example, event procedures in the Normal template only occurif the attached template is the Normal template.

If an auto macro exists in a document and the attached template, onlythe auto macro stored in the document will execute. If an event procedure for adocument event exists in a document and its attached template, both eventprocedures will run.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值