我正在通过 Excel VBA 插件创建 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
这对我有用:
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
Set rng = 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 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
一旦
rng
成功,直接与 Find
合作可能会更好。