Hello, I am attempting to search for a specific text string in a document and wherever found, replace that text with a document property/field.
I am trying to re-purpose code I found on Mr. Greg Maxey's website. My attempt is shown below. In the example the text string in question is a company name. The idea is to replace the manually typed company name in the document with the Company document property. That way, if the company name property value is changed, an update all fields action will update all instances of the name throughout the document.
The problem with the code below is, while the program finds and deletes each instance of the text string, it does not replace that string with the property field in each location; rather, it inserts a Company field instance for each occurrence of the found text string, but all insertions are made back-to-back wherever the cursor happened to be in the document when the code is run.
Perhaps rather than range, I should be trying the find method, but I don't know how to do that.
Any help would be most appreciated.
Private Sub cmdDone_Click()
Dim rngStory As Word.range
Dim lngValidate As Long
'Fix the skipped blank Header/Footer problem as provided by Peter Hewett.
lngValidate = ActiveDocument.Sections(1).Headers(1).range.StoryType
Dim myTgtText As String
If optCompany.value = True Then myTgtText = lblCompanyValue.Caption
'Iterate through all story types in the current document.
For Each rngStory In ActiveDocument.StoryRanges
'Iterate through all linked stories.
Do
With rngStory.Find
.Text = myTgtText
.Replacement.Text = ""
Selection.Fields.Add range:=Selection.range, Type:=wdFieldEmpty, _
Text:="DOCPROPERTY Company", PreserveFormatting:=True
.Wrap = wdFindContinue
.Execute Replace:=wdReplaceAll
End With
'Get next linked story (if any).
Set rngStory = rngStory.NextStoryRange
Loop Until rngStory Is Nothing
Next
lbl_Exit:
Exit Sub
End Sub
Doug