How to insert table and bookmark into Word, one per page

坚强是说给别人听的谎言 提交于 2020-05-17 06:43:10

问题


I have a Word document that starts with one table on page one, and then depending on the data in an Excel file, I want to start inserting tables in subsequent pages, and just before each table, I want to insert a text blurb or caption. I'm using a bookmark to insert this text. After inserting the table, I want to add a page break, so that I can start the next table insertion on the next page.

The result I get from the code below places the tables and bookmarks in incorrect order, on seemingly random pages, and in seemingly random order, and the tables are not dimensioned properly (not 6X5 as they should be, but somehow they're 3x3). How can I control the tables, bookmarks, and page breaks to order the document properly?

'FROM EXCEL
Dim wd as New Word.Document
Dim doc as Word.Document
Dim Rng as Range
Dim d as Variant
dim datMin, datMax as Date
datMin = "04/01/2020"
datMax = "04/05/2020"

Set doc = wd.Documents.Open("myFile")
Set Rng = doc.Range(0, 0)
For d = datMin To datMax
    Set Rng = Rng.GoTo(What:=wdGoToPage, Which:=wdGoToAbsolute, Count:=(d - datMin + 2)) 'Go to top of page
    doc.Bookmarks.Add "D" & d - datMin + 2, Rng  'BOOKMARK NAMES ARE "D2", "D3", etc.
    Rng.Bookmarks("D" & d - datMin + 2).Range.Text = d   'Place Text in bookmark
    doc.Tables.Add Rng, 6, 5  'Add table
    Rng.InsertBreak wdPageBreak  'Add pagebreak
Next d


回答1:


Your unqualified use of 'Dim Rng as Range' implies to the code that you're referring to an Excel range. Try:

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


来源:https://stackoverflow.com/questions/61220439/how-to-insert-table-and-bookmark-into-word-one-per-page

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!