PDA

View Full Version : How to insert table in the next page?



applevb
04-13-2023, 06:51 AM
Hi all,

I need to output tables and paragraph dynamically in the word document.

I tried the code below, but cursor does not move to next page and nothing is output on the second page. Could you please take a look?
thank you !:yes


'Dim wdApp As Object
'Set wdApp = CreateObject("word.Application")
'Early Binding
Dim wdApp As Word.Application
Set wdApp = New Word.Application
With wdApp
.Visible = True
.Activate
.Documents.Add
With .Selection
.Tables.Add _
Range:=wdApp.Selection.Range, _
NumRows:=1, NumColumns:=3, _
DefaultTableBehavior:=wdWord9TableBehavior, _
AutoFitBehavior:=wdAutoFitContent
'Set table format 3 rows
For counter = 1 To 12
.TypeText Text:="Cell " & counter
If counter <> 12 Then
.MoveRight Unit:=wdCell
End If
Next
End With
'Selection.GoTo What:=wdGoToBookmark, Name:="TC_Table"
Selection.GoTo What:=wdGoToPage, Which:=lNextPage
Selection.TypeText vbCrLf & vbCrLf
Selection.TypeText vbCrLf & vbCrLf
Selection.TypeText vbCrLf & vbCrLf
Selection.TypeText "This is test."
.Tables.Add _
Range:=wdApp.Selection.Range, _
NumRows:=1, NumColumns:=3, _
DefaultTableBehavior:=wdWord9TableBehavior, _
AutoFitBehavior:=wdAutoFitContent
'Set table format 3 rows
For counter = 1 To 12
.TypeText Text:="Cell " & counter
If counter <> 12 Then
.MoveRight Unit:=wdCell
End If
Next
End With

Aussiebear
04-13-2023, 12:26 PM
Welcome to the VBAX forum applevb. Please note that we normally wrap supplied code by using the # icon. Two methods available to you, either insert your text and highlight then click the # icon, or click the # icon and then insert your code.

Dave
04-13-2023, 03:39 PM
Hi applevb and Welcome to this forum. I'll share some code that Macropod provided me. You put all your tables in the doc then use styles so the tables don't split your table on to different pages. At least I think that's what your after? Dave

'prevent tables from splitting page
Dim Otbl as Object, Ocel as Object
For Each Otbl In WdApp.ActiveDocument.Tables
Otbl.Range.Paragraphs.keepwithnext = True
For Each Ocel In Otbl.Rows.Last.Range.Cells
Ocel.Range.Paragraphs.Last.keepwithnext = False
Next Ocel
Next Otbl

Dave
04-13-2023, 03:43 PM
Missed the edit... here's some code to generate multiple tables...
VBA/Macros help for an Excel to Word document generator. Need to create and find/replace X tables, where X is the numberof rows TRUE in another sheet | MrExcel Message Board (https://www.mrexcel.com/board/threads/vba-macros-help-for-an-excel-to-word-document-generator-need-to-create-and-find-replace-x-tables-where-x-is-the-numberof-rows-true-in-another-sheet.1221522/#post-5974042)
Dave