我正在尝试搜索Word文档并将正则表达式匹配项替换为一系列静态超链接。
例如,如果我得到"A-1"
的正则表达式匹配项,我想用带有"A-1"
和Anchor = "A-1"
的超链接替换Address = "https://www.my_website.com/A-1"
字符串。我的RegEx匹配项可能是"A-1", "A-2", "A-3", etc
。
我熟悉RegEx,但对VBA还是很陌生。我到目前为止所拥有的:
Sub FindAndHyperlink()
Dim RegEx As Object
Set RegEx = CreateObject("VBScript.RegExp")
RegEx.Global = True
RegEx.Pattern = "([A][\-])([0-9])"
Set Matches = RegEx.Execute(ActiveDocument.Range.Text)
For Each Match In Matches
ActiveDocument.Range.Text = RegEx.Replace(ActiveDocument.Range.Text, (ActiveDocument.Hyperlinks.Add Anchor:=Match, Address:="https://www.my_website.com/" & Match))
Next
End Sub
该代码无法编译,因为它期望在)
之后出现ActiveDocument.Hyperlinks.Add
。
我认为问题在于RegEx.Replace()
方法期望使用(String, String)
个参数而不是(String, Hyperlink object)
,但是我不确定解决该问题的最佳方法。
任何帮助将不胜感激。
答案 0 :(得分:0)
尝试:
Sub FindAndHyperlink()
Application.ScreenUpdating = False
Const HLnk As String = "https://www.my_website.com/"
With ActiveDocument.Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "A-[0-9]{1,}"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchWildcards = True
.Execute
End With
Do While .Find.Found
.Hyperlinks.Add Anchor:=.Duplicate, Address:=HLnk & .Text, TextToDisplay:=.Text
.Start = .Hyperlinks(1).Range.End
.Find.Execute
Loop
End With
Application.ScreenUpdating = True
End Sub
答案 1 :(得分:0)