I have a word document named "Template.docx" in the same path of ThisWorkbook.
In the excel file in sheet1 there are four columns: First column for naming the template. The second column will have a value that would be replaced. The third column as the second one. The fourth column will have a link to an image (full path)
Say I have these values in row1:
First Template ---- Yasser ---- Khalil ----- C:\Users\User\Desktop\Sample.jpg
Second Template --- Hans--- Tutor --- C:\Users\User\Desktop\Sample2.jpg
I have the following code that changes the Template itself and do the replacement of columns B & C and here's the code
Code: Select all
Sub Test()
Dim objWd As Object, objDoc As Object, strName As String
With Application.FileDialog(1)
.Filters.Clear
.Filters.Add "Word Documents", "*.doc*"
.InitialFileName = ThisWorkbook.Path & "\*.doc*"
If .Show Then strName = .SelectedItems(1) Else Exit Sub
End With
On Error Resume Next
Set objWd = GetObject(Class:="Word.Application")
If objWd Is Nothing Then Set objWd = CreateObject(Class:="Word.Application")
On Error GoTo 0
objWd.Visible = True
Set objDoc = objWd.Documents.Open(strName)
With ThisWorkbook.Worksheets("Sheet1")
objDoc.Content.Find.Execute FindText:="XXXXX", ReplaceWith:=.Range("B1").Value, MatchWholeWord:=False, Replace:=2
objDoc.Content.Find.Execute FindText:="YYYYY", ReplaceWith:=.Range("C1").Value, MatchWholeWord:=False, Replace:=2
End With
'objDoc.Close SaveChanges:=True
End Sub
And finally and this is most important to insert the image in the word document at a specific place (not sure what's the best approach for that point .. )