VBA 在 Word 2010 中查找单词并替换为超链接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23869679/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 03:14:49  来源:igfitidea点击:

VBA find word and replace with a Hyperlink in Word 2010

vbahyperlinkms-wordword-vbaword-2010

提问by mr3k

I've a word document with some text. At some paragraphs I've words that I want to add the hyperlink to. Here's an example:

我有一个包含一些文本的 Word 文档。在某些段落中,我想添加超链接。下面是一个例子:

The book "When the sun goes up", ABC-1212321-DEF, have been released today.......

《当太阳升起时》一书,ABC-1212321-DEF,今天已经发布......

The "ABC-1212321-DEF" should be found and apply a hyperlink as follows: http://google.com/ABC-sometext-1212321-anothertext-DEF

应找到“ABC-1212321-DEF”并应用如下超链接:http: //google.com/ABC-sometext-1212321-anothertext-DEF

All the strings in the document starts with "ABC-" and ends with "-DEF".

文档中的所有字符串都以“ABC-”开头,以“-DEF”结尾。

Thanks in advanced.

提前致谢。

EDIT:

编辑:

This is what I've got this far:

这是我到目前为止所得到的:

Sub InsertLinks()
Dim r As Range
Dim SearchString As String

Set r = ActiveDocument.Range
SearchString = "ABC-"
With r.Find
.MatchWildcards = True
Do While .Execute(findText:=SearchString, Forward:=True) = True
ActiveDocument.Hyperlinks.Add Anchor:=r, _
Address:=Replace(r.Text, " ", ""), _
SubAddress:="", ScreenTip:="", TextToDisplay:=r.Text
With r
.End = r.Hyperlinks(1).Range.End
.Collapse 0
End With
Loop
End With
End Sub

This now detects ABC- and add some random link. But need to get the number between ABC- and -DEF. The length is not the same.

现在检测 ABC- 并添加一些随机链接。但是需要得到ABC-和-DEF之间的数字。长度不一样。

采纳答案by mr3k

SOLUTION

解决方案

This is the code that solved my problem:

这是解决我的问题的代码:

Sub InsertLinksTB()
Dim Rng As Range
Dim SearchString As String
Dim EndString As String
Dim Id As String
Dim Link As String


Set Rng = ActiveDocument.Range
SearchString = "ABC-"
EndString = "-DEF"
    With Rng.Find
    .MatchWildcards = True
        Do While .Execute(findText:=SearchString, Forward:=False) = True
            Rng.MoveStartUntil ("ABC-")
            Rng.MoveEndUntil (" ")
            'MsgBox (Rng.Text)
            Id = Split(Split(Rng.Text, "ABC-")(1), "-DEF")(0)
            'MsgBox (Id)
            Link = "http://google.com/" & Id

                ActiveDocument.Hyperlinks.Add Anchor:=Rng, _
                Address:=Link, _
                SubAddress:="", ScreenTip:="", TextToDisplay:=Rng.Text
                Rng.Collapse wdCollapseStart


        Loop
    End With

End Sub

So if the text "ABC-1234-DEF" is found in the text, it will hyperlink this text with http://google.com/1234

因此,如果在文本中找到文本“ABC-1234-DEF”,它将将此文本与http://google.com/1234超链接

Hope this is helpful for someone.

希望这对某人有帮助。