Word VBA:在该文档类模块和常规模块之间共享变量?
在Word 2013中,我需要在此文档和常规模块之间共享一个变量(ccID)。代码如下: “项目(Toto)”→ “Microsoft Word对象”→ “本文件”: “项目(Toto)”→ “模块”→ “模块1”:Word VBA:在该文档类模块和常规模块之间共享变量?,vba,variables,ms-word,Vba,Variables,Ms Word,在Word 2013中,我需要在此文档和常规模块之间共享一个变量(ccID)。代码如下: “项目(Toto)”→ “Microsoft Word对象”→ “本文件”: “项目(Toto)”→ “模块”→ “模块1”: 当UpdateContentControl运行时,ccID脱离上下文。如何在此文档中的代码和常规模块之间共享变量?这对我来说很好: Public子文档\u ContentControlAfterAdd(ByVal NewContentControl作为ContentControl_
当UpdateContentControl运行时,ccID脱离上下文。如何在此文档中的代码和常规模块之间共享变量?这对我来说很好:
Public子文档\u ContentControlAfterAdd(ByVal NewContentControl作为ContentControl_
ByVal InUndoRedo(作为布尔值)
NewContentControl.Range.Shading.BackgroundPatternColor=wdColorYellow
端接头
但是,它看起来像是清除了占位符文本,因此下面介绍了如何使用OnTime执行此操作:
本文件:
Option Explicit
Public Sub Document_ContentControlAfterAdd(ByVal NewContentControl As ContentControl, ByVal InUndoRedo As Boolean)
Static ccID As String
Dim alertTime As Variant
' You can't affect document content while within this event, so save CC ID and create a timer that calls code to execute after the event has finished.
ccID = NewContentControl.ID
alertTime = Now + TimeValue("00:00:01")
Application.OnTime alertTime, "UpdateContentControl"
End Sub
选项显式
Dim LastCC
Public Sub Document_ContentControlAfterAdd(ByVal NewContentControl作为ContentControl,ByVal InUndoRedo作为Boolean)
LastCC=NewContentControl.id
Application.OnTime when:=现在+时间序列(0,0,1)_
名称:=“UpdateContentControl”
端接头
公共属性Get lastaddcc()
LastAddedCC=LastCC
端属性
模块:
Public子UpdateContentControl()
模糊id
id=ThisDocument.LastAddedCC
Debug.Print“UpdateContentControl以id开头:”&id
ThisDocument.ContentControls(id).Range.Shading.BackgroundPatternColor=wdColorYellow
端接头
NewContentControl.Range.Shading.BackgroundPatternColor=wdColorYellow
在事件处理程序中对我来说效果很好-无需延迟着色。这就成功了。谢谢打字错误:以选项Explicit
开头的代码进入“ThisDocument”,而不是“ThisWorkbook”,因为这是Word,不是Excel。
' Give any newly-added content control a yellow background for user-friendliness
' (Called by ThisDocument -> Document_ContentControlAfterAdd)
Public Sub UpdateContentControl()
MsgBox ("UpdateContentControl started")
ActiveDocument.ContentControls(ccID).Range.Shading.BackgroundPatternColor = wdColorYellow
End Sub