Word全局模板VBA: ContentControlOnExit事件不触发时,放置在启动文件夹



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

有什么想法,这应该如何修改工作预期从启动文件夹?

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

我以前也遇到过这个问题。您不会让它像那样工作,它只会在加载的"*"上触发ContentControlOnExit事件的事件。dotm - file本身。"

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

您必须创建一个类clsDocument,其中有一个变量Public WithEvents p_Document as Word.Document。在你的类内部,你可以监听你的p_Document的事件ContentControlOnExit,并把你的代码放在那里(在你的例子中是MsgBox ("Fired"))。

接下来,你必须听一般事件"AutoExec"one_answers"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和一个WithEvents WordApplication as Word.Application,您就可以对事件做出反应。所有这些代码都放到。com -file中,所以全局模板文件。

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

最新更新