Word bookmark names global search & replace

J

jkriordan

Can anybody tell me how to search and replace the names of bookmarks in a
Word 07 docx?

Halfway into a very large document, I figured out a very useful naming
scheme. Now I want to revise the names earlier bookmarks without redoing each
one individual.
 
D

DaveLett

Hi,

I think you're looking for something like the following:

Dim oBk As Bookmark

For Each oBk In ActiveDocument.Bookmarks
oBk.Name = "Test_" & oBk.Name
Next oBk

HTH,
Dave
 
G

Greg Maxey

The .Name property of a bookmark is "read only." I think the only way you
could do this is to cycle through the existing bookmark collection and
recreate the bookmarks with the new name. Perhaps something like this:

Sub ScratchMaco()
Dim i As Long
Dim oRng As Word.Range
Dim j As Long
For j = ActiveDocument.Bookmarks.Count To 1 Step -1
Set oRng = ActiveDocument.Bookmarks(j).Range
oRng.Text = ActiveDocument.Bookmarks(j).Range.Text
ActiveDocument.Bookmarks.Add "My_new_name" & j, oRng
Next
End Sub
 
G

Greg Maxey

Dave,

Does that not generate a compile error. Can't assign to read only property?
 
F

Fumei2 via OfficeKB.com

I believe this code will fail. Maybe in 2007 it works, but it certainly does
not work for earlier versions. The .Name property of Bookmarks is read-only.

You can not change the names of bookmarks. You must use the range of the
bookmark and make a new bookmark (giving the new bookmark the name you want).
You also have to be careful about deleting the old bookmark names because of
the way Word deals with the bookmark collection. It is best to do your
creation of new bookmarks, THEN delete the old ones with something like:

Sub ChangeBM()
Dim oBk As Bookmark
Dim oBM_Delete()
Dim j As Long
Dim var

For Each oBk In ActiveDocument.Bookmarks
' make a new bookmark using SAME range
ActiveDocument.Bookmarks.Add _
Name:="Test_" & oBk.Name, _
Range:=oBk.Range
' add the old name to an array
ReDim Preserve oBM_Delete(j)
oBM_Delete(j) = oBk.Name
j = j + 1
Next oBk

' now delete the old bookmarks
For var = 0 To UBound(oBM_Delete())
ActiveDocument.Bookmarks(oBM_Delete(var)).Delete
' note this deletes the bookmark
' NOT the range
Next
End Sub
 
M

macropod

Hi Gerry,

We seem to have been down this path recently in another forum:

Sub RenameBookmarks()
Dim BM_Names()
Dim i As Long
With ActiveDocument
For i = 1 To .Bookmarks.Count
ReDim Preserve BM_Names(i)
BM_Names(i) = .Bookmarks(i).Name
Next
For i = 1 To .Bookmarks.Count
With .Bookmarks(BM_Names(i))
.Range.Bookmarks.Add Name:="NEW_" & .Name, Range:=.Range
.Delete
End With
Next
End With
End Sub
 

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