-1

下面的代码放置在 .dotm 模板文件的 ThisDocument 单词对象中。直接打开文件时,每次退出活动文档中的内容控件时,都会按预期触发以下事件。但是,当模板放置在 Startup 文件夹中并自动打开时,不会触发该事件。

关于如何修改它以从 Startup 文件夹中按预期工作的任何想法?

Private Sub Document_ContentControlOnExit(ByVal ContentControl As _
ContentControl, Cancel As Boolean)
    MsgBox ("Fired")
End Sub
4

1 回答 1

0

我过去也遇到过这个问题。你不会让它像那样工作,它只会触发ContentControlOnExit你加载的“* .dotm”文件本身的事件。

要对宏文档之外发生的更改做出反应,您必须使用一个相当复杂的结构,我将向您简要解释一下。

您必须创建一个clsDocument有变量的类Public WithEvents p_Document as Word.Document。在您的班级内,您然后收听您的事件ContentControlOnExit并将p_Document您的代码放在那里(在您的情况下为MsgBox ("Fired").

接下来,您必须收听一般事件“AutoExec”和“AutoOpen”以及“Application_DocumentChange”。在所有这些事件中,您基本上只需将全局变量设置为p_Document传递给事件的文档或(如果没有传递给事件处理程序的文档)活动文档的值。由于所有这些事件反应或多或少都做同样的事情,所以在你的宏模块中创建一个新过程,如下所示:

Public g_clsWordDocument                     As clsDocument

Public Sub SetUpDocumentEvents(Optional ByRef a_Document As Word.Document = Nothing)

If Application.Documents.Count > 0 Then
   If a_Document Is Nothing Then Set a_Document = ActiveDocument
   Set g_clsDocument = New clsDocument
   Set g_clsDocument.p_Document = a_Document
End If

End Sub

ThisDocument然后,在您的宏文件中创建以下过程。

Option Explicit

Private g_clsWordApplication            As clsApplication


Public Sub AutoExec()

Set g_clsWordApplication = New clsApplication
Set g_clsWordApplication.WordApplication = Word.Application

Call modYourModule.SetUpDocumentEvents

End Sub

Private Sub Document_New()
   Call modYourModule.SetUpDocumentEvents
End Sub

Private Sub Document_Open()
   Call modYourModule.SetUpDocumentEvents
End Sub

Public Sub AutoOpen()
   Call modYourModule.SetUpDocumentEvents
End Sub

像这样,您可以捕获文档事件。正如您在AutoExec函数中看到的,应用程序对象也是如此,只需clsAplication使用 an创建一个新对象,WithEvents WordApplication as Word.Application您就可以对事件做出反应。所有这些代码都进入您的 dotm 文件,因此是全局模板文件。

通过这种方式,您可以对您想要的事件做出反应。虽然我还没有找到解决这个问题的另一种方法,但我仍然对它的实现方式不满意。如果有其他选择可以解决您的问题,我强烈建议您尝试另一种方式。

于 2016-09-14T09:14:47.097 回答