Lawyer Luddite
asked on
Word bookmark refinement
A previous answer gave me this piece of code to replace every instance of a given text with a sequentially numbered set of bookmarks. This works if rng.Text = ""
However I want replace the text XXX with the word DATA (inside the new bookmark) but if I change
rng.Text = ""
to
rng.Text = "DATA"
then I only get one bookmark and the other instances of XXX are ignored. What should I be doing?
Sub ReplaceWithBookmarks()
Dim rng As Range
Dim iBookmarkSuffix As Integer
Dim strBookMarkPrefix
strBookMarkPrefix = "BM"
Set rng = ActiveDocument.Range
With rng.Find
.Text = "XXX"
Do While .Execute
rng.Text = "" 'clear the "XXX" (optional)
iBookmarkSuffix = iBookmarkSuffix + 1
ActiveDocument.Bookmarks.A dd strBookMarkPrefix & iBookmarkSuffix, rng
Loop
End With
End Sub
The second related issue is that I do not want to lose the bookmarks when I put replacement text into them. The code below puts in the text but I lose the bookmark.
For Each MyBook In ActiveDocument.Bookmarks
sbook = UCase(Left(MyBook.Name, 2))
Select Case sbook
Case "BM"
MyBook.Select
MyBook.Range.Text = "his"
End Select
Next
I want to keep the bookmark with the word "his" inside it
I found a cumbersome solution adding another bookmark then later renaming it back to the original but I am sure there is a simpler way?
However I want replace the text XXX with the word DATA (inside the new bookmark) but if I change
rng.Text = ""
to
rng.Text = "DATA"
then I only get one bookmark and the other instances of XXX are ignored. What should I be doing?
Sub ReplaceWithBookmarks()
Dim rng As Range
Dim iBookmarkSuffix As Integer
Dim strBookMarkPrefix
strBookMarkPrefix = "BM"
Set rng = ActiveDocument.Range
With rng.Find
.Text = "XXX"
Do While .Execute
rng.Text = "" 'clear the "XXX" (optional)
iBookmarkSuffix = iBookmarkSuffix + 1
ActiveDocument.Bookmarks.A
Loop
End With
End Sub
The second related issue is that I do not want to lose the bookmarks when I put replacement text into them. The code below puts in the text but I lose the bookmark.
For Each MyBook In ActiveDocument.Bookmarks
sbook = UCase(Left(MyBook.Name, 2))
Select Case sbook
Case "BM"
MyBook.Select
MyBook.Range.Text = "his"
End Select
Next
I want to keep the bookmark with the word "his" inside it
I found a cumbersome solution adding another bookmark then later renaming it back to the original but I am sure there is a simpler way?
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Great - that does what I need - thanks again for helping me understand how this all works
ASKER
However the second solution fails because it is on an infinite loop. Adding the bookmark name back just puts it back into the range so it goes on for ever.