The following very helpful code from @macropod (at bottom) works well to insert tables/bookmarks/page breaks, generated in Excel, into the end of a Word document (How to insert table and bookmark into Word, one per page). I'm trying to modify the code to insert into the middle of an original 2 page document, with one table on one page and a second table on page 2, and a few empty paragraphs and a pagebreak in between. The result should be each new bookmark/table combo is iteratively inserted into a new page in between the original two tables.
Dim wdApp As New Word.Document, wdDoc As Word.Document, wdRng As Word.Range, wdTbl As Word.Table
Dim d As Long, StrBkMk As String, datMin As Date, datMax As Date
datMin = "04/01/2020": datMax = "04/05/2020"
Set wdDoc = wdApp.Documents.Open("myFile")
With wdDoc
For d = datMin To datMax
StrBkMk = "D" & d
Set wdRng = .Characters.Last
With wdRng
.Collapse wdCollapseStart
.Text = CDate(d) 'Place Text in bookmark
.Bookmarks.Add StrBkMk, .Duplicate
.Collapse wdCollapseEnd
.InsertBefore vbCr
Set wdTbl = .Tables.Add(.Duplicate, 6, 5) 'Add table
wdTbl.Range.Characters.Last.Next.InsertBefore Chr(12) 'Add pagebreak
End With
Next d
.Characters.Last.Previous.Text = vbNullString
End With
I tried replacing:
Set wdRng = .Characters.Last
with
Set wdRng = .Characters.First
Set wdRng = wdRng.GoTo(What:=wdGoToPage, Which:=wdGoToAbsolute, Count:=(d - datMin + 2))
where (d - datMin + 2) is the page number, but this doesn't work. It puts the first table/bookmark/page in the right place, but then it puts the subsequent tables/bookmarks/pagebreaks at the end of the document, and they overlap each other. Any ideas what I'm doing wrong and how I can fix this?