Here's a head-splitter: I'm trying to programmatically create hidden bookmarks for existing headings in a doc, so that I can create hyperlinks elsewhere in the doc that point to these bookmarks. (I want to use hyperlinks instead of cross-references so I can specify my own 'Display Text' for the links, which isnt possible using cross-refs).
I want my bookmarks to be named after the headings they relate to, with a custom prefix. Example:
- style: Heading1
- heading text: Entrance & Hallway
- bookmark name: _Hd1_Entrance_&_Hallway
I'm specifying a custom prefix to make each bookmark unique to it's style, so I can then have 2 matching headings in the doc, so long as they are in different heading styles. (example: _Hd1_Entrance_&_Hallway and _Hd3_Entrance_&_Hallway)
The catch is: if my heading contains special chars like '&', I get a 'Bad Bookmark Name' error, which I understand, and this is documented on the web. I'm only allowed to use a limited character set.
So how come if I manually create a hyperlink using Word's own dialog, selecting a 'Place In This Document' such as a heading like "Entrance & Hallway", Word manages this no problem? Once the Hlink is created, I can now see the hidden bookmark associated with this Hlink in Word's 'Bookmarks' dialog - and it's quite happily named "_Entrance _&_Hallway". This confounds me!
Anyone have an explanation? I'd really like to be able to leverage this same functionality, but cannot fathom how. Any help is greatly valued! Thanks,
Sub ScratchPad_Bookmarks()
Dim doc As Document
Dim rng As Range
Dim sHdName As String
Dim sBmName As String
Set doc = ActiveDocument
'Insert a heading at start of document
sHdName = "Entrance & Hallway"
doc.Range.InsertBefore sHdName & vbCr
doc.Paragraphs(1).Range.Style = doc.Styles("Heading 1")
'Find the above heading in the active document
Set rng = doc.Range
With rng.Find
.ClearFormatting
.Text = sHdName
.Style = "Heading 1"
If Not .Execute Then
'Heading not found, so quit
Exit Sub
End If
End With
'rng has collapsed to the found heading, so create a bookmark
'rng.Select 'debug
sBmName = Replace(rng.Text, " ", "_")
rng.Collapse wdCollapseStart
rng.Bookmarks.Add sBmName
'sBmName contains '&' so this throws a Runtime error:
'5828: Bad Bookmark Name (as expected)
End Sub
The above doesnt work. However to test the manual operation yourself is easy. Just create a heading that includes a '&' character, style it as Heading 1. In the next paragraph, insert a hyperlink using Word's own dialog. Select Place In This Doc and select the heading you just created. Shouldn't be a problem. Now open Word's Bookmark dialog, enable the Hidden Bookmarks view, and voila: a hidden bookmark with a '&' character. (Wd 2010) Say what?!
&
into a string? Could you show us the line of code where you try to define the bookmark? – Matteo NNZ