0
votes

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?

1

1 Answers

2
votes

Embarrasingly, it turns out the fix is quite easy.

Instead of as above

Set wdRng = .Characters.Last

It's as simple as replacing with:

Set wdRng = .Paragraphs(2).Range

Or better still, insert a Section Break (Insert->Break->Section Break Type) where you want to add stuff (tables, bookmarks, page breaks, etc). in the middle of the document, and then use:

Set wdRng = .Sections(2).Range
. . . 
. . . 

And to make sure the order of insertions is correction (not in reverse order), need the following changes:

    Set Rng = .Sections((d - datMin) + 1).Range 'Go to next section each loop
    . . . 
    . . . 

    wdTbl.Range.Characters.Last.Next.InsertBreak wdSectionBreakNextPage  'To add pagebreak . . . instead of .InsertBefore Chr(12) as in original code