【问题标题】:Use VBA to replace RegEx strings with hyperlinks in Word在 Word 中使用 VBA 将 RegEx 字符串替换为超链接
【发布时间】:2019-03-22 10:55:37
【问题描述】:

我正在尝试搜索 word 文档并将正则表达式匹配替换为一系列静态超链接。

例如,如果我得到"A-1" 的正则表达式匹配,我想用Anchor = "A-1"Address = "https://www.my_website.com/A-1" 的超链接替换"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),但我不确定解决这个问题的最佳方法。

任何帮助将不胜感激。

【问题讨论】:

  • 我不认为 replace 对于你想要做的事情有意义。我认为清除Match.Range 处的文本然后在Match.Range 的位置添加超链接会更有意义
  • @Marcucciboy2 你会怎么做?我在想'For Each Match In Matches''Match.Text = ""' ActiveDocument.Hyperlinks.Add Anchor:=Match, Address:="my_website.com" & Match'
  • Matches 是否真的从RegEx.Execute 接收到该正则表达式的每个匹配项的范围?
  • 是的,这就是我想要的目标
  • 你不能单独使用正则表达式,正则表达式只适用于纯文本。在文档中找到索引并尝试在该位置添加超链接。

标签: regex vba hyperlink ms-word


【解决方案1】:

试试:

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

【讨论】:

    【解决方案2】:

    我刚刚对此进行了测试,对我来说效果很好。

    ([a-z _:/.A-Z-1-9]+)
    

    注意大写和小写,加上 1-9(包括 1 到 9)以及斜线和句点等字符。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-14
      • 2019-04-20
      • 2014-07-15
      • 2022-06-24
      • 1970-01-01
      • 2017-10-15
      • 1970-01-01
      • 2012-01-11
      相关资源
      最近更新 更多