Convert Text into Fields

L

Lyle

Is there a way programmatically to search a document for a specific text
string ( ie "[CustomerName]") and change all instances of that to be a field
tied back to Custom Document Property "CustomerName"? I would like the
search to cover the body of the document. If it will not complicate things
greatly, I would like to include the headers and footers.

I have already tried to do it by a Do Until Loop (see code below), but it
behaves erratically (appears to repeat about 10 times in one spot, work
correctly in some spots, and ignores others).

Any thoughts would be appreciated.

Lyle
-----------------------------------------

Sub ReplaceCustomerNameToFLD()
Dim pRange As Word.Range
Dim iLink As Long
iLink = ActiveDocument.Sections(1).Headers(1).Range.StoryType
For Each pRange In ActiveDocument.StoryRanges
Do
Selection.Find.ClearFormatting
With Selection.Find
.Text = "[CustomerName]"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = True
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute
Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, Text:= _
"DOCPROPERTY CustomerName ", PreserveFormatting:=True
Set pRange = pRange.NextStoryRange
Loop Until pRange Is Nothing
Next
End Sub
-------------------------------------------
 
J

Jezebel

The problem with your code is that you are iterating the storyranges, but
carrying out your Find on the selection, which is remaining wherever it is
when you call the macro. Try structuring your code along these lines --

Dim pStoryRange As Word.Range
Dim pFindRange As Word.Range

For Each pStoryRange In ActiveDocument.StoryRanges
Do
Set pFindRange = pStoryRange
With pFindRange.Find
.ClearFormatting
.Text = "[CustomerName]"
.Format = False

Do While .Execute
pFindRange.Fields.Add Range:=pFindRange, _
Type:=wdFieldEmpty,
_
Text:="DOCPROPERTY
CustomerName "
Loop
End With

Set pStoryRange = pStoryRange.NextStoryRange
Loop Until pStoryRange Is Nothing
Next
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top