【问题标题】:How to add Word hyperlinks from Excel cells using VBA (hyperlink.add)如何使用 VBA (hyperlink.add) 从 Excel 单元格添加 Word 超链接
【发布时间】:2019-06-02 04:48:31
【问题描述】:

我想使用 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

谢谢!

【问题讨论】:

    标签: excel vba ms-word


    【解决方案1】:

    我想我找到了问题所在。您指的是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】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2014-12-03
      • 2015-02-11
      • 1970-01-01
      • 1970-01-01
      • 2017-05-02
      • 1970-01-01
      • 2016-08-23
      • 1970-01-01
      • 2016-05-21
      相关资源
      最近更新 更多