我有一个相当大的 Word 文件(+1,100 页),其中包含媒体报道的纯文本链接。例如,Word 文档包含:
新闻领袖报(美联社)弗吉尼亚州一名在第一次值班时牺牲的警察安息 http://www.newsleader.com/story/news/nation-now/2016/03/01/va-police-officer-who-died-her-first-shift-laid-rest/81183272/ 03.01.16
利文斯顿日报弗吉尼亚州一名在第一次值班时牺牲的警察安息 http://www.livingstondaily.com/story/news/nation-now/2016/03/01/va-police-officer-who-died-her-first-shift-laid-rest/81183272/ 03.01.16
(在 Word 文档中,这些链接不是超链接,只是文本!)
目前,我们获取数据并合并到 Word 的方式是将链接格式化为纯文本而不是超链接。
我想使用 VBA 将所有这些纯文本链接转换为可点击的超链接,保留链接文本(例如,保留链接锚文本的超链接)。
我找到了一些使用特定链接来查找和替换特定字符串的代码示例,例如:
Sub FindAndHyperlink()
'define the style
Dim strStyle As String
strStyle = "Normal"
'set the search range
Dim rngSearch As Range
Set rngSearch = ActiveDocument.Range
'set the search string
Dim strSearch As String
strSearch = "tuesday"
'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
但是,我不知道如何动态改变搜索/选择/替换功能。
我想要的是:
- 搜索“http”
- 选择整个超链接
- 设为超链接,不改变锚文本
- 对所有纯文本超链接重复上述操作
有什么建议么?
答案1
尝试这个:
Sub Hyperlinker()
Dim Rng As Range
Set Rng = ActiveDocument.Range
With Rng.Find
Do While .Execute(findText:="http:", Forward:=False) = True
Rng.MoveEndUntil (" ")
ActiveDocument.Hyperlinks.Add _
Anchor:=Rng, _
Address:=Rng.Text, _
SubAddress:="", _
ScreenTip:="", _
TextToDisplay:=Rng.Text
Rng.Collapse wdCollapseStart
Loop
End With
End Sub
替换完所有内容后,您可能必须保存并重新打开 Word 文档才能使链接开始发挥作用。
答案2
根据@Techie007 的回答和@RJo 的询问,稍微更挑剔的版本:
Sub Hyperlinker()
Dim Rng As Range
Dim startsOfUrlArray As Variant
Dim startOfUrl As Variant
startsOfUrlArray = Array("https:", "http:", "www")
For Each startOfUrl In startsOfUrlArray
Set Rng = ActiveDocument.Range
With Rng.Find
Do While .Execute(findText:=startOfUrl, Forward:=False) = True
Rng.MoveEndUntil " "
ActiveDocument.Hyperlinks.Add _
Anchor:=Rng, _
Address:=Rng.text, _
SubAddress:="", _
ScreenTip:="", _
TextToDisplay:=Rng.text
Rng.Collapse wdCollapseStart
Loop
End With
Next startOfUrl
End Sub
答案3
@Luciano,
Paul Beverley 和他的编辑团队有一个宏,用于将参考列表中的纯文本 URL 转换为超链接。它确实会删除 URL 中的“http://”和“https://”部分。但如果您需要保留这些内容,只需在宏中删除这些行即可。
以下是链接:https://www.wordmacrotools.com/macros/U/URLlinker.txt。
干杯!