View Single Post
 
Old 02-23-2018, 04:41 AM
gmayor's Avatar
gmayor gmayor is offline Windows 10 Office 2016
Expert
 
Join Date: Aug 2014
Posts: 4,137
gmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud of
Default

The following should work

Code:
Sub Macro1()
ReplaceWithDocVar "Mary", "TheName"
End Sub


Sub ReplaceWithDocVar(strFind As String, strVarName As String)
Dim oStory As Range
    For Each oStory In ActiveDocument.StoryRanges
        With oStory.Find
            Do While .Execute(FindText:=strFind, MatchWholeWord:=True)
                oStory.Text = ""
                oStory.Fields.Add Range:=oStory, _
                                  Type:=wdFieldDocVariable, _
                                  Text:=Chr(34) & strVarName & Chr(34), _
                                  PreserveFormatting:=True
                oStory.Collapse 0
            Loop
        End With
        If oStory.StoryType <> wdMainTextStory Then
            While Not (oStory.NextStoryRange Is Nothing)
                Set oStory = oStory.NextStoryRange
                With oStory.Find
                    Do While .Execute(FindText:=strFind, MatchWholeWord:=True)
                        oStory.Text = ""
                        oStory.Fields.Add Range:=oStory, _
                                          Type:=wdFieldDocVariable, _
                                          Text:=Chr(34) & strVarName & Chr(34), _
                                          PreserveFormatting:=True
                        oStory.Collapse 0
                    Loop
                End With
            Wend
        End If
    Next oStory
    Set oStory = Nothing
lbl_Exit:
    Exit Sub
End Sub
__________________
Graham Mayor - MS MVP (Word) (2002-2019)
Visit my web site for more programming tips and ready made processes www.gmayor.com
Reply With Quote