My ultimate goal: Have Excel_Doc_A and Word_Doc_A. Excel_Doc_A will use VBA to refer to Word_Doc_A, Find certain text values (in this example, " TITLE "), insert a hyperlink into that text field, and change the text to what is indicated in Excel_Doc_A, and then save the Word_Doc_A as a NEW file, Word_Doc_B, that has all the text replaced and hyperlinks included.
My code is below. I'm getting an error, "Compile Error: Argument Not Optional on Find". The piece of code that's generating this error is the
.Find
on the line
Set myFind = myRange.Find
Any ideas? Thanks!
Public Sub testing_1()
Dim documentApplication As Word.Application
Dim documentDocument As Word.Document
Set narApplication = CreateObject("word.application")
Set narDocument = narApplication.Documents.Open(ThisWorkbook.Path & "/document_template.docx")
Dim TITLE As String
Dim myRange As range
Dim myFind As Find
Dim filePath As String
TITLE = range("B1")
'For each value, find it's value in the blankdocument
Set myRange = narDocument.Content
Set myFind = myRange.Find
With myFind
.Text = "__TITLE__"
searchResult = .Execute
.Replacement.Text = TITLE
End With
narDocument.Hyperlinks.Add Anchor:=myRange, Address:="http://www.google.com", TextToDisplay:="__TITLE__ "
filePath = ThisWorkbook.Path & "/document_test.docx"
narDocument.SaveAs2 Filename:=filePath
'Cleanup
narDocument.Quit False
Set narApplication = Nothing
Set narDocument = Nothing
End Sub
Dim myRange As Range
is implicitly As Excel.Range
. You get a compile error because Set myFind = myRange.Find
is referencing the Excel Range.Find
method. You need members from the Word object model.
Early-binding:
Dim myRange As Word.Range
Dim myFind As Word.Find
Late-binding:
Dim myRange As Object
Dim myFind As Object
It would be best to be consistent.
Early-binding:
Dim documentApplication As Word.Application
Dim documentDocument As Word.Document
Set narApplication = New Word.Application
Late-binding:
Dim documentApplication As Object
Dim documentDocument As Object
Set narApplication = CreateObject("word.application")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.