I recently asked a similar question but thanks to a comment I have made some updates. However, I am running into some issues.
I am attempting to use Word bookmarks in a "template" to auto-populate the text that is bookmarked based on excel values. My Macro does almost everything I want it to do, except some of the text is not showing up in the output. I have a template (word doc) that looks like this:
..date..
..ID..
..Address Line 1.
..Address Line 2..
..Address Line 3..
Dear Customer,
I want the "..date.." to be replaced with the current date, "..ID.." with the ID (from an excel workbook), and so on. Here is my code:
' Filepath to the data and template
Const FilesPath As String = "filepath"
Const TemplateFile As String = "temp.docx"
Sub CreateWordDocuments()
Dim prenom As String
Dim nom As String
Dim firstname As String
Dim lastname As String
Dim add1 As String
Dim add2 As String
Dim add3 As String
Dim id As String
Dim wd As Word.Application
Dim doc As Word.Document
Dim tday
Dim NomRange As Range, NomCell As Range, ws As Worksheet
Set ws = ActiveSheet
Set NomRange = ws.Range("A2", ws.Cells(Rows.Count, 1).End(xlUp))
Set wd = New Word.Application
wd.Visible = True
For Each NomCell In NomRange.Cells
Set doc = wd.Documents.Open(FilesPath & TemplateFile)
With NomCell.EntireRow
firstname = .Columns("C").Value
lastname = .Columns("B").Value
add1 = .Columns("X").Value
add2 = .Columns("Y").Value
add3 = .Columns("Z").Value
id = .Columns("A").Value
tday = Date
If .Columns("J").Value = "Keep" Then
doc.Bookmarks("date").Range.Text = tday
doc.Bookmarks("id").Range.Text = id
doc.Bookmarks("name").Range.Text = firstname & lastname
doc.Bookmarks("add1").Range.Text = add1
doc.Bookmarks("add2").Range.Text = add2
doc.Bookmarks("add3").Range.Text = add3
doc.SaveAs2 FilesPath & firstname & ".pdf", wdExportFormatPDF
doc.Close False
End If
End With
Next NomCell
wd.Quit
End Sub
However, when I run this Macro, The address line bookmarks are removed from the final word output- the only things there are the date and ID. Any thoughts as to what may be happening?