Sunday 26 January 2020

microsoft word - Find all instances of a text and make it a hyperlink with a macro

Required


I want to find all occurrences of a single text in a MS Word document, make each occurence a hyperlink and change the generic hyperlink style to one of my chosing.


What I have


As I have no idea on how to achieve the above requirement as a whole, I started on a part of it, namely finding a single instance and adapting it.


So, I recorded a macro, that resulted in the following code. That code I adapted so that the sub could take parameters for the hyperlinkText and the hyperlink subaddress:


Sub AutoDetectHyperlinksForText(hyperlinkText As String, subaddress As String, style As String)
Selection.Find.ClearFormatting
With Selection.Find
.Text = hyperlinkText
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute
ActiveDocument.Hyperlinks.Add Anchor:=Selection.Range, Address:="", _
subaddress:=subaddress, ScreenTip:="", TextToDisplay:= _
hyperlinkText
Selection.MoveLeft Unit:=wdWord, Count:=1, Extend:=wdExtend
Selection.Style = ActiveDocument.Styles(style)
End Sub

With this it is easy to Call the sub for multiple word instances, such as:


Call AutoDetectHyperlinksForText("broadcasts", "_broadcastService", "Subtle Emphasis")

Question


How can I adapt this macro so that it checks the entire document?


Bonus question


Is there a way to modify the above script so that I can store my selection, and remove the need for the .MoveLeft?


In pseudocode that would be something like this:


Dim mySelect as Selection
mySelect = Selection.Find.Execute
ActiveDocument.Hyperlinks.Add Anchor:=mySelect.Range, Address:="", _
subaddress:=subaddress, ScreenTip:="", TextToDisplay:= _
hyperlinkText
mySelect.Style = ActiveDocument.Styles("Subtle Emphasis")

No comments:

Post a Comment

How can I VLOOKUP in multiple Excel documents?

I am trying to VLOOKUP reference data with around 400 seperate Excel files. Is it possible to do this in a quick way rather than doing it m...