问题描述
我有一个带有一些文本的Word文档.在某些段落中,我有一些要添加超链接的词.这是一个示例:
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:
今天出版了《太阳升起》这本书,ABC-1212321-DEF…….
The book "When the sun goes up", ABC-1212321-DEF, have been released today.......
应找到"ABC-1212321-DEF"并应用超链接,如下所示: http://google.com/ABC-sometext-1212321-anothertext-DEF
The "ABC-1212321-DEF" should be found and apply a hyperlink as follows: http://google.com/ABC-sometext-1212321-anothertext-DEF
文档中的所有字符串均以"ABC-"开头,以"-DEF"结尾.
All the strings in the document starts with "ABC-" and ends with "-DEF".
非常感谢.
这是我到目前为止所要做的:
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
现在可以检测到ABC-并添加一些随机链接.但是需要获取ABC-和-DEF之间的数字.长度不一样.
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.
推荐答案
解决方案
这是解决我的问题的代码:
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
因此,如果在文本中找到文本"ABC-1234-DEF",它将使用 http://google.com/1234
So if the text "ABC-1234-DEF" is found in the text, it will hyperlink this text with http://google.com/1234
希望这对某人有帮助.
这篇关于VBA在Word 2010中找到单词并替换为超链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!