1
votes

I am trying to add several tables to a word document, using vba. So far I have code that is fine in adding one table. But when I add a second, it does not add a table but rather adds cells to the previous table.

But I need separate tables on each page ...

What I have so far:

Sub addIntroTable(wdDoc As Document)
    Dim myRange As Object
    Set myRange = wdDoc.Content
    myRange.Collapse Direction:=wdCollapseEnd
    With wdDoc
        .Tables.Add Range:=myRange, NumRows:=3, NumColumns:=1
        With .Tables(.Tables.Count)
            .Cell(1, 1).SetHeight RowHeight:=100, _
                                  HeightRule:=wdRowHeightExactly
            ... more table formatting (shortened for reading)..
            .Cell(1, 1).Range.Text = "some text"
        End With
    End With
End Sub

I have some more subs for different table styles but they all do the same. When calling a single sub, it adds the table to the end of the document and there is one of those paragraph break signs still behind it.

When I call this or one of the other subs right after it, the rows just get added to the previous table. Formatting is then applied to the whole table.

Do I have to change something with the insertion point? Or am I missing something else?

2

2 Answers

2
votes

Yes, you need to move the insertion point.

There needs to be at least one paragraph between each table. The code in your question adds a table to the end of the document. This will leave a single paragraph after the table. If you insert another table at the beginning of that paragraph Word will join the two tables.

So what you need to do is add another paragraph and then add your table into the new paragraph.

-1
votes
  dim MyRange as Range  
    MyRange = oWordTable.Range
    MyRange.Collapse(WdCollapseDirection.wdCollapseEnd)
    MyRange.Move(WdUnits.wdCharacter, 1)
    MyRange.Select()
    MyRange.InsertParagraph()
    MyRange.InsertBreak(WdBreakType.wdPageBreak)