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!