如何使用VBA(hyperlink.add)从Excel单元格添加Word超链接

3

我想使用Excel VBA根据Excel单元格范围在Word文档中创建链接。但是当它到达hyperlinks.add行时,会出现"run-time error ‘450’: Wrong number of arguments or invalid property assignment"的错误提示。

几乎相同的代码在Word VBA中运行良好。我不明白错误信息。虽然我对Excel VBA非常熟悉,但Word VBA的选择和范围让我感到困惑。

我在下面的代码示例中使用字符串而不是范围,在每种情况下,代码都会成功地将文本插入到test.docx文档的末尾,但是Word VBA会在下面插入带有链接的文本,而Excel VBA代码则无法在hyperlinks.add行处执行。

这是Excel VBA代码,目前无法正常工作:

Sub wordLinkFromExcelRanges()
Dim wApp As Word.Application, wDoc As Word.Document
Dim linkText As String, link As String
  linkText = "google"
  link = "http://www.google.com"
  Set wApp = New Word.Application
  wApp.Visible = True
  Set wDoc = wApp.Documents.Open("C:\test\test.docx")
  With wApp.Selection
    .EndKey 6, 0 'go to end of doc
    .TypeParagraph
    .TypeText "text without link"
    .TypeParagraph
    wDoc.Hyperlinks.Add Anchor:=Selection.Range, Address:=link, _
    SubAddress:="", ScreenTip:="", TextToDisplay:=linkText
  End With
  wApp.Quit
  Set wDoc = Nothing
  Set wApp = Nothing
End Sub

以下是可用的 Word VBA 代码:

Sub wordLinkFromWord()
Dim wD As Document
Dim linkText As String, link As String
linkText = "google"
link = "http://www.google.com"
Set wD = ActiveDocument
With Selection
  .EndKey 6, 0
  .TypeParagraph
  .TypeText "text without link"
  .TypeParagraph
  wD.Hyperlinks.Add Anchor:=Selection.Range, Address:=link, _
  SubAddress:="", ScreenTip:="", TextToDisplay:=linkText
End With
End Sub

谢谢!

2个回答

2
我认为我找到了问题所在。您正在引用Selection.Range,但我认为在这种情况下没有选择任何内容。
您可以尝试使用以下代码替代:

Sub wordLinkFromExcelRanges()
    Dim wApp        As Word.Application: Set wApp = New Word.Application
    Dim wDoc        As Word.Document
    Dim linkText    As String: linkText = "google"
    Dim link        As String: link = "http://www.google.com"

    wApp.Visible = True
    Set wDoc = wApp.Documents.Open("C:\test\test.docx")
    With wApp.Selection
      .EndKey 6, 0
      .TypeParagraph
      .TypeText "text without link"
      .TypeParagraph
      wDoc.Hyperlinks.Add Anchor:=.Range, Address:=link, SubAddress:="", ScreenTip:="", TextToDisplay:=linkText
    End With
    wApp.Quit
End Sub

谢谢你的帮助,Ryan。是的,你找到了答案并且几乎和我同时发布了。我会保留我的解决方案,但是会给你功劳。 - Tony M
是的,我看到了。很高兴你解决了它 :) - Ryan Wildry

0
我想通了:问题行中的"Selection"应该改为"wApp.Selection"

wDoc.Hyperlinks.Add Anchor:=wApp.Selection.Range, Address:=link, _ SubAddress:="", ScreenTip:="", TextToDisplay:=linkText

制作一个最小示例的过程对我很有帮助——也许这个简单的示例对其他人也有帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接