'Insert Document Property Object

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 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 found that the following VBA code 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.



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1