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



我想使用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行处失败。

这是不起作用的ExcelVBA代码:

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:testtest.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

这是正在工作的单词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

谢谢!

我想

我发现了这个问题。你指的是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:testtest.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

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

wDoc.Hyperlinks.Add Anchor:=wApp.Selection.Range, Address:=link, _子地址:=", 屏幕提示:=", 文本显示:=链接文本

做一个最小的例子的过程帮助了我——也许简单的例子也会帮助其他人。

最新更新