I am to take ownership of a 275 page Word document, which once converted as PDF is used to navigate through information within a classification scheme, including figures and explanations. Many of these explanations are cross referenced within the document. My predecessor has been slowly doing this by hand, for each cross reference first making a bookmark at the destination, then going to the source and creating a hyperlink to that bookmark.
I was thinking of automating at least the bookmarking part, since all of the destinations are already in bold within the document. The format of these is for instance 1/02 07, to which my predecessor has associated bookmark name B1_0207, and I would like to keep this format (it has been done to overcome Word's limitations). So I need to add a B at the beginning, replace / by _ and to remove all spaces
I found a macro which I adapted.
Sub ScratchMacro()
'A basic Word macro coded by Greg Maxey
Dim oRng As Range, oRngDup As Range, oBookName As Range
Set oRng = Selection.Range
Set oRngDup = oRng.Duplicate
Set oBookName = oRng
With oRng.Find
.ClearFormatting
.Font.Bold = True
Do While .Execute
oBookName = Replace(oBookName.Text, "/", "_")
oBookName = Replace(oBookName.Text, " ", "")
oBookName = ("B" & (oBookName))
If oRng.InRange(oRngDup) Then
ActiveDocument.Bookmarks.Add oBookName.Text, oRng
oRng.Collapse wdCollapseEnd
Else
Exit Do
End If
Loop
End With
lbl_Exit:
Exit Sub
End Sub
I immediately get an error for the bookmark name, and I have even seen it change the original text in the document itself, which I absolutely do not want to happen.
I thought of automating the creation of hyperlinks too, since the reference to hyperlink would be written as, in this same example, 1/02 07 but not in bold, so probably easy to find and match (although some explanations direct to other scheme, such as for instance A47G 1/02 07, would have to be excluded).
I have not tried automating the hyperlinking yet.
Your code to reformat the found text into a usable bookmark name is replacing that text. Clearer if you include the default Text
property for oBookName
:
oBookName.Text = Replace(oBookName.Text, "/", "_")
...actually replaces the text in the found range.
Try this instead:
Sub ScratchMacro()
Dim oRng As Range, BookName As String, doc As Document
Set doc = ActiveDocument
Set oRng = doc.Range 'or use current Selection...
With oRng.Find
.ClearFormatting
.Font.Bold = True
.Wrap = wdFindStop 'stop when the end of the content is reached
Do While .Execute
'oRng.Select
'read range to string and replace / and spaces
BookName = Replace(oRng.Text, "/", "_")
BookName = "B" & Replace(BookName, " ", "")
doc.Bookmarks.Add BookName, oRng
Loop
End With
End Sub