使用Excel向Word文档添加超链接

92dk7w1h  于 2023-10-22  发布在  其他
关注(0)|答案(1)|浏览(162)

我正在通过Excel插件创建Word文档,并希望将Word文档中的某些短语更改为超链接。我没有得到一个错误,但我的代码不工作。

Dim linkText    As String: linkText = "https://cdphe.colorado.gov/drinking-water-water-hauler-rule"
    Dim link        As String: link = "https://cdphe.colorado.gov/drinking-water-water-hauler-rule"

    With appWD.ActiveDocument.Content.Find
        .Execute FindText:="http://www.colorado.gov/cdphe/hauler"
        With appWD.Selection
          .EndKey 6, 0
          .TypeParagraph
          .TypeText "text without link"
          .TypeParagraph
          .Hyperlinks.Add Anchor:=.Range, Address:=link, SubAddress:="", ScreenTip:="", TextToDisplay:=linkText
        End With
    End With
ru9i0ody

ru9i0ody1#

这对我很有效:

Sub Tester()
    
    Const linkText As String = "https://cdphe.colorado.gov/drinking-water-water-hauler-rule"
    Const link As String = "https://cdphe.colorado.gov/drinking-water-water-hauler-rule"
    
    Dim rng As Range, appWD As Object

    'set appWD to Word instance...
    
    Set rng = appWD.ActiveDocument.Content 'range to be searched
    If rng.Find.Execute(FindText:="http://www.colorado.gov/cdphe/hauler") Then
        rng.Select ' `rng` is now the found text: select it
        With appWD.Selection
          .EndKey 6, 0
          .TypeParagraph
          .TypeText "text without link"
          .TypeParagraph
          .Hyperlinks.Add Anchor:=.Range, Address:=link, _
                SubAddress:="", ScreenTip:="", TextToDisplay:=linkText
        End With
    End If
    
End Sub

不过,在Find成功之后,最好直接使用rng

相关问题