compyutech
compyutech

Reputation: 581

Adding a page in MS Word document using VBA adds extra pages

I have MS word file with macro having table in the first page. (Table is created using labels).

But When cells in table is not sufficient I want to add another page, with the similar table in it.

So I am trying to code as below

ActiveDocument.Sections(1).Range.Copy

ActiveDocument.Sections.Add.Range.Paste

But this code some time changes the format of first page. And also create third blank page with second page having content of first.

Can any body let me know how to add only a page having same content of first page, without changes in first page.

Thanks

Upvotes: 1

Views: 15057

Answers (1)

user1379931
user1379931

Reputation:

The table will flow into the next page automatically, and you can specify repeating heading rows as well.

But assuming you need a new table...

Your original question needs some clarifications (see some points below), but see if the following code spoils your formatting:

Sub copytable1()
Dim rtarget As Word.Range
With ActiveDocument
  Set rtarget = .Range(.Content.End - 1, .Content.End - 1)
  rtarget.InsertBreak Type:=Word.WdBreakType.wdPageBreak
  Set rtarget = .Range(.Content.End - 1, .Content.End - 1)
  rtarget.FormattedText = .Tables(1).Range.FormattedText
  Set rtarget = Nothing
End With
End Sub

It assumes that

  • the table you want to copy is the first table in the document
  • you just want to insert a new page at the end of the document and insert a copy of the table after that. If your document can already be multi-page, you would need significantly different code.

When creating editable Word documents, as a "good practice," you would use a paragraph style with the "Page Break Before" property set to achieve the break, rather than a hard page break as I have done.

Alternatively,

Sub copytable3()
Dim rtarget As Word.Range
With ActiveDocument
  Set rtarget = .Range
  rtarget.Collapse wdCollapseEnd
  rtarget.InsertParagraphAfter
  Set rtarget = .Range
  rtarget.Collapse wdCollapseEnd
  rtarget.ParagraphFormat.PageBreakBefore = True
  Set rtarget = .Range
  rtarget.Collapse wdCollapseEnd
  rtarget.InsertParagraphAfter
  Set rtarget = .Range
  rtarget.Collapse wdCollapseEnd
  rtarget.ParagraphFormat.PageBreakBefore = False
  Set rtarget = .Range
  rtarget.Collapse wdCollapseEnd
  rtarget.Select
  rtarget.FormattedText = .Tables(1).Range.FormattedText
  Set rtarget = Nothing
End With
End Sub

Upvotes: 3

Related Questions