简体   繁体   中英

VBA for changing doc properties Word

I am trying to create a code that need to change a custom document property in a word document. This custom document property is the information that must be inserted in the document but sometimes need to be changed as requested. So far I have created the code for inserting the custom document property, it works fine, see below.

Sub AddCustomDocProperty()

Selection.Fields.Add _
    Range:=Selection.Range, _
    Type:=wdFieldEmpty, _
    Text:="DOCPROPERTY  ""ProjectName"" ", _
    PreserveFormatting:=False
    
End Sub

The custom document property is named as ProjectName which will be linked with a specific field where the user will input the project name, eg New Screwdriver

Let's say the custom document property shows New Screwdriver and I need to change to New Screwdriver 2021.

How can I write a code that change the docproperty based on the new input given in Project name field?

I tried to find something in the forum but I did not find anything.

Thanks in advance.

A user can't easily change the value of such a field by simply typing. Whatever additional text they type will fall outside the field. Then it's difficult for you to retrieve with VBA. Consider using a content control, formfield, or even a bookmarked table cell for their input instead.

But to answer your question, this will update a custom document property:

Sub SetProp()
    ActiveDocument.CustomDocumentProperties("ProjectName").value = "New Screwdriver 2021"
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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