Home > Enterprise >  Word VBA: Insert Document Property Object
Word VBA: Insert Document Property Object

Time:01-12

In my Word (Office 365) document, I can insert a Quick Part for the company name by clicking Insert / Quick Parts / Document Property / Company. I'd like to create a macro to do that, so I can pop a button on my Quick Access toolbar to make it one click not four. When I record the process, the macro does not register the insert. I've found that the following VBA inserts the current text of the field, but not the content control itself:

ActiveDocument.Content.InsertAfter ActiveDocument.BuiltInDocumentProperties(wdPropertyCompany)

I figure there must a single line of VBA that would insert the Company Quick Part field into my document, as if I had done those four clicks, but I can't figure it out - please could you help?

CodePudding user response:

The trick is to map the content control to the Company

Sub insertCompanyCC()

On Error GoTo err_insert

Dim cc As ContentControl
Set cc = ActiveDocument.ContentControls.Add(wdContentControlText, Selection)
With cc
   .Title = "Company"
   .XMLMapping.SetMapping "/ns0:Properties[1]/ns0:Company[1]"
End With

exit_insert:
    Exit Sub

err_insert:
    Select Case Err
        Case 4605
             MsgBox "Please move your cursor outside of the content control.", vbExclamation
        Case Else
            Err.Raise Err.Number, Err.Source
    End Select
    Resume exit_insert
End Sub

e.g. /ns1:coreProperties[1]/ns0:creator[1] would insert the author.

  •  Tags:  
  • Related