代码之家  ›  专栏  ›  技术社区  ›  Tony M

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

  •  2
  • Tony M  · 技术社区  · 6 年前

    我想使用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 文档,但当单词vba插入链接低于该链接的文本时,Excel vba代码在 超链接 线。

    以下是不起作用的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
    

    下面是正在工作的单词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 回复  |  直到 6 年前
        1
  •  1
  •   Ryan Wildry    6 年前

    我想我发现了问题。你指的是 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
    
        2
  •  0
  •   Tony M    6 年前

    我想出来了: "Selection" 在问题行应该是 "wApp.Selection"

    wdoc.hyperlink.add锚定:=wapp.selection.range,地址:=link,,_ 子地址:=“”,屏幕提示:=“”,文本显示:=linktext

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