【问题标题】:Search sentence and replace for hyperlink in Word VB.NET在 Word VB.NET 中搜索句子并替换超链接
【发布时间】:2015-12-17 17:41:23
【问题描述】:

我试图替换或搜索并添加超链接以在 Word 文档中指定句子。我尝试使用此代码。无论如何,代码只会改变第一个找到的单词,而不是全部在文档中:

       Dim r As Word.Range
    r = Globals.ThisAddIn.Application.ActiveDocument.Content
    With r.Find
        .ClearFormatting()
        .Text = ("MyWordA MyWordB")
        .MatchWholeWord = True
        .Forward = True
        .Execute()
        'If .Found = True Then r.Hyperlinks.Add(r, "http:\\www.whatever", , "Displayed text")
        Do While .Execute(Forward:=True) = True
            r.Hyperlinks.Add(r, "http:\\www.whatever", , "Displayed text")
            'r.Font.ColorIndex = Word.WdColorIndex.wdBlue 'works for all(?)
        Loop
    End With

当我想在循环中只找到一个单词时,然后代码找到第一个:

    doc = Globals.ThisAddIn.Application.ActiveDocument
    Dim r As Word.Range = doc.Range
    Dim ww As Word.Range
    For Each ww In r.Words
        If ww.Text = "MyWord" Then _
          ww.Hyperlinks.Add(ww, "http:\\www.whatever", , "Displayed text")
    Next

谁能告诉我如何搜索所有文本以替换/添加超链接到我正在寻找的所有文本?

【问题讨论】:

    标签: vb.net hyperlink ms-word


    【解决方案1】:

    问题是您一遍又一遍地寻找相同的文本。在您的循环中,添加超链接后,您需要在添加的超链接之后移动范围。最简单的方法是通过调用来折叠范围

    r.Collapse(WdCollapseDirection.wdCollapseEnd)
    

    要解决此类问题,选择当前范围会很有帮助,这样您就可以了解正在发生的事情。

    Do While .Execute(Forward:=True) = True
    
        ' select range for troubleshooting
        r.Select()
        r.Hyperlinks.Add(r, "http:\\www.whatever", , "Displayed text")
    
        ' move the range after the link
        r.Collapse(WdCollapseDirection.wdCollapseEnd)
    Loop
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-15
      • 2013-01-01
      • 2014-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-22
      相关资源
      最近更新 更多