Link to home
Start Free TrialLog in
Avatar of Lawyer Luddite
Lawyer LudditeFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Word VBA replace text string with bookmarks

I need to programmatically do a find and replace in a document to replace a given string with a set of bookmarks. Been all over Google trying to find an answer and every answer is the other way round (i.e. replace bookmark with string instead of replace string with bookmark)

For example I wan to replace all instances of text "XXX" with bookmarks progressively named, BM1,BM2,BM3 etc

I can work out how to do a find/replace and how to insert bookmarks but I am struggling to combine the two.

I found the code below in another EE answer which does a similar thing with Fields but I don't understand the object library sufficient well to alter this to workwith bookmarks - can anyone help please.

Dim rngStoryType As Range
    Dim rngCurrentStory As Range
    Dim rngFind As Range
    ' Go through all story ranges in the document, including shapes,
    ' headers & footers.
    For Each rngStoryType In ActiveDocument.StoryRanges
        Set rngCurrentStory = rngStoryType 'set rngCurrentStory to first range in story
        Do
            Set rngFind = rngCurrentStory
            With rngFind.Find
                .Text = "XXX"
                Do While .Execute
                    ActiveDocument.Fields.Add rngFind, wdFieldRef, "BM_Project_Name"
                    rngFind.Collapse wdCollapseEnd
                    rngFind.End = rngCurrentStory.End
                Loop
            End With
            rngCurrentStory.Fields.Update
            Set rngCurrentStory = rngCurrentStory.NextStoryRange
        Loop Until rngCurrentStory Is Nothing
    Next rngStoryType
ASKER CERTIFIED SOLUTION
Avatar of GrahamSkan
GrahamSkan
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Lawyer Luddite

ASKER

Perfect that is exactly what I want. Many thanks.