How to add Word hyperlinks from Excel cells using VBA (hyperlink.add)

时间:2019-01-07 13:56:44

标签: excel vba ms-word

I want to use Excel VBA to make links in a Word document based upon Excel cell ranges. But when it gets to the hyperlinks.add line I get "run-time error ‘450’: Wrong number of arguments or invalid property assignment".

Almost the exact same code works fine in Word VBA. I don't understand the error message. While I'm quite familiar with Excel VBA, Word VBA selections and ranges confuse me.

I made code examples below using strings instead of ranges, in each case the code inserts text successfully at the end of the test.docx document but while the Word VBA inserts text with a link below that, the Excel VBA code fails at the hyperlinks.add line.

Here is the Excel VBA Code that is not working:

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

Here is the Word VBA code that is working:

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

Thanks!

2 个答案:

答案 0 :(得分:1)

I think I found the issue. You are referring to Selection.Range but I don't think anything is selected in this context.

You can try this instead:

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

答案 1 :(得分:0)

I figured it out: the "Selection" in the problem line should be "wApp.Selection"

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

The process of making a minimal example helped me -- maybe the simple example will help others too.