Reputation: 1
I am new to working with VBA and Word 2010.
I have a Word document with some text fields using Content Controls (i.e. rich text control).
I want one of them named (Title) as "testbox" to be a counter of how many times the document has been printed.
I have some code from Excel that works. Is it possible to use this in MS Word? How do I communicate with the Content Control instead of a cell in 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
Upvotes: 0
Views: 2085
Reputation: 25693
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. Document_BeforePrint, for example, and 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. 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).
A ContentControl can be picked up by its Title using the Document.SelectContentControlsByTitle method. 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)
Upvotes: 0