必須
MS Word 文書内の単一テキストのすべての出現箇所を検索し、各出現箇所をハイパーリンクにして、一般的なハイパーリンク スタイルを任意のスタイルに変更したいと考えています。
私が持っているもの
上記の要件を全体としてどのように達成するかについてはわかりませんので、まずはその一部、つまり単一のインスタンスを見つけてそれを適応させることから始めました。
そこで、マクロを記録して、次のコードを作成しました。このコードを、サブルーチンがパラメータを受け取れるように変更しました。ハイパーリンクテキストハイパーリンクサブアドレス:
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
これを使えば簡単に電話複数の単語インスタンスのサブ。例:
Call AutoDetectHyperlinksForText("broadcasts", "_broadcastService", "Subtle Emphasis")
質問
このマクロを調整してドキュメント全体をチェックするにはどうすればよいでしょうか?
ボーナス質問
上記のスクリプトを変更して、選択内容を保存し、 の必要性をなくす方法はありますか.MoveLeft
?
疑似コードでは次のようになります。
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")
答え1
これは「google」(googlesやgoogledではない)という単語を検索し、ハイパーリンクします。http:\\google.com
スタイルも適用されます
Sub FindAndHyperlink()
'define the style
Dim strStyle As String
strStyle = "Subtle Emphasis"
'set the search range
Dim rngSearch As Range
Set rngSearch = ActiveDocument.Range
'set the search string
Dim strSearch As String
strSearch = "google"
'set the target address for the hyperlink
Dim strAddress As String
strAddress = "http:\\google.com"
With rngSearch.Find
Do While .Execute(findText:=strSearch, MatchWholeWord:=True, Forward:=True) = True
With rngSearch 'we will work with what is found as it will be the selection
ActiveDocument.Hyperlinks.Add Anchor:=rngSearch, Address:=strAddress
.Style = ActiveDocument.Styles(strStyle) 'throw the style on it after the link
End With
rngSearch.Collapse Direction:=wdCollapseEnd
'keep it moving
Loop
End With
End Sub
当然、引数を渡したい場合は、それを実行すればパラメータで呼び出すことができますが、これが必要な基礎となります。