简体   繁体   English

内容控件MS Word

[英]Content Controls MS Word

I am new to working with VBA and Word 2010. 我刚接触VBA和Word 2010。

I have a Word document with some text fields using Content Controls (ie rich text control). 我有一个使用内容控件(即富文本控件)的带有某些文本字段的Word文档。

I want one of them named (Title) as "testbox" to be a counter of how many times the document has been printed. 我希望其中一个名为“标题”的标题为“ testbox”,以作为打印文档次数的计数器。

I have some code from Excel that works. 我有一些有效的Excel代码。 Is it possible to use this in MS Word? 可以在MS Word中使用它吗? How do I communicate with the Content Control instead of a cell in Excel? 如何与内容控件而不是Excel中的单元格进行通信?

Private Sub Workbook_BeforePrint(Cancel As Boolean) 
  Cancel = True 
  Application.EnableEvents = False 
  ActiveSheet.PrintOut 
  Range("A1").Value = Range("A1").Value + 1
  Application.EnableEvents = True 
End Sub

The basic approach of the code you show should work in Word, you just need to look up the appropriate names of the objects, methods and properties. 您显示的代码的基本方法应该可以在Word中运行,您只需要查找对象,方法和属性的适当名称即可。 Document_BeforePrint, for example, and ActiveDocument.Print. 例如,Document_BeforePrint和ActiveDocument.Print。

Word doesn't have an EnableEvents property so you need to create your own method or methods for turning off the events you define at the Application level. Word没有EnableEvents属性,因此您需要创建自己的方法来关闭在应用程序级别定义的事件。 How those methods should look and what they require is part of the discussion about how to use Application level events in Office - part of the VBA Language Reference ( https://msdn.microsoft.com/en-us/library/office/ff821218.aspx ). 这些方法的外观以及它们的要求是有关如何在Office中使用应用程序级事件的讨论的一部分-VBA语言参考( https://msdn.microsoft.com/zh-cn/library/office/ff821218的一部分) .aspx )。

A ContentControl can be picked up by its Title using the Document.SelectContentControlsByTitle method. 可以使用Document.SelectContentControlsByTitle方法按其标题选择ContentControl。 This returns an array of content controls having the same Title. 这将返回具有相同标题的内容控件数组。 If you have only the one, then something like this: 如果只有一个,则如下所示:

Dim cc As Word.ContentControl
Dim ccs as Word.ContentControls
Set ccs = ActiveDocument.SelectContentControlsByTitle("testbox")
Set cc = ccs(1)
cc.Range.Text = Cstr(CInt(cc.Range.Text) + 1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM