View Single Post
 
Old 04-28-2012, 01:23 PM
Marrick13 Marrick13 is offline Windows XP Office 2010 32bit
Competent Performer
 
Join Date: Jun 2006
Posts: 103
Marrick13 will become famous soon enough
Default VBA to copy bookmark-hyperlinks to plain text strings

I want to be able to copy a hyperlink tied to a bookmark to all occurrences of a text string entered in an inputbox, and I don't know whether the code should search and select all finds and replace them with the link or if there are better ways.

In the document I'm working on, I have 16 instances of the plain text "Chapter 22" that I want to convert to HYPERLINK \l "EmotionalGuidanceScale" (still displaying "Chapter 22" as the text) so I can click on any of them and navigate to the EmotionalGuidanceScale bookmark.

I started the code for the inputbox and counter, but that's as far as I got. It just occurred to me that after entering the text to be converted, I should display the bookmark list so the bookmark can be selected (not that I necessarily know how to do that!), but I still have the unresolved issue of actually copying the link to the text strings.

Code:
Sub CopyFieldCode()
Dim Text As String, MyDoc As String, t As String, count As Long, i As Integer

MyDoc = ActiveDocument.Range.Text

Text = InputBox("Enter text to find (case sensitive)")

If Text = "" Then
    Exit Sub
    End If

 t = Replace(MyDoc, Text, "")
    count = (Len(MyDoc) - Len(t)) / Len(Text)
If count = 0 Then
    MsgBox "There were no occurrences of " & Text
    Exit Sub
    End If
    
For i = 1 To count

[Here is where I need help; the code snippet below doesn't work]

ActiveDocument.Hyperlinks.Add Anchor:=Selection.Range, Address:="", _
        SubAddress:="EmotionalGuidanceScale", ScreenTip:="", TextToDisplay:= _
        Text
    End With
    
Next i
End Sub
Reply With Quote