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