I have a set of database in Excel and want to copy them into a Word template with bookmarks through VBA. Individual Word Documents will be generated.
Coding please find as below
Option Explicit
'change this to where your files are stored
Const FilePath As String = "C:\Users\User\Desktop\"
Dim wd As New Word.Application
Dim PersonCell As Range
Sub CreateWordDocuments()
'create copy of Word in memory
Dim doc As Word.Document
wd.Visible = True
Dim PersonRange As Range
'create a reference to all the people
Range("A4").Select
Set PersonRange = Range(ActiveCell, ActiveCell.End(xlDown))
'for each person in list
For Each PersonCell In PersonRange
'open a document in Word
Set doc = wd.Documents.Open(FilePath & "Template.docx")
'go to each bookmark and type in details
CopyCell "FirstName", 1
CopyCell "LastName", 2
CopyCell "Company", 3
CopyCell "Address", 4
'save and close this document
doc.SaveAs2 FilePath & "person " & PersonCell.Value & " (" & Format(Now, "yyyy-mm-dd") & ").docx"
doc.Close
Next PersonCell
wd.Quit
MsgBox "Created files in " & FilePath & "!"
Set doc = Nothing
Set wd = Nothing
End Sub
Sub CopyCell(BookMarkName As String, ColumnOffset As Integer)
'copy each cell to relevant Word bookmark
wd.Selection.GoTo What:=wdGoToBookmark, Name:=BookMarkName
wd.Selection.TypeText PersonCell.Offset(0, ColumnOffset).Value
End Sub
Now, I want to generate one Word document with multiple pages. How to modify the coding to generate one word document with multiple pages?
Microsoft documentation:
Update: