PDA

View Full Version : [SOLVED:] Inserting N number of Word Tables 1 after the other with VBA



jtukes
11-04-2013, 08:07 AM
Hi All,

I am trying to figure out how to insert a user specified amount "N" number of Tables, one after the other in a Word Doc using VBA. Basically, I have to duplicate the same Table multiple times depending on how many times the process is run. I tried using a copy/paste method (see below) and that didnt seem to work, so I am wondering if there is any other way to have the number of Tables inserted be dependent on a user input? Any help would be greatly appreciated.


Thanks,

jtukes


If UserForm1.ufPhases.Value > 0 Then ' ufPhases is a Textbox
ThisDocument.Tables(9).Select
Selection.Copy
For q = 1 To UserForm1.ufPhases.Value
Selection.EndKey Unit:=wdStory
If Selection.Next(wdCharacter, -1) <> Chr(13) Then Selection.TypeParagraph
Selection.Paste
Next
End If

fumei
11-04-2013, 03:20 PM
Dim lngRows As Long
Dim lngCols As Long
Dim var

lngRows = ActiveDocument.Tables(9).Rows.Count
lngCols = ActiveDocument.Tables(9).Columns.Count

If UserForm1.ufPhases.Value > 0 Then
For var = 1 To UserForm1.ufPhases.Value
Selection.Collapse 0
ActiveDocument.Tables.Add Range:=Selection.Range, NumRows:=lngRows, _
NumColumns:=lngCols, DefaultTableBehavior:=wdWord9TableBehavior, _
AutoFitBehavior:=wdAutoFitFixed
With Selection
.EndKey Unit:=wdStory
.TypeParagraph
.Collapse 0
End With
Next
End If Assuming from your example that you want to have the same number of rows and columns as Table9.

macropod
11-04-2013, 03:53 PM
Assuming you want exact replicas of Table 9, try something based on:

Sub DuplicateTables()
Dim Rng As Range, i As Long, j As Long
i = CLng(InputBox("How many replica tables?"))
With ActiveDocument
Set Rng = .Tables(9).Range
With Rng
.Start = .Start - 1
.Copy
For j = 1 To i
.Collapse wdCollapseEnd
.Paste
'.Tables(1).Range.Delete
Next
End With
End With
End Sub
Note: By uncommenting '.Tables(1).Range.Delete', the code clears the pasted tables' content.

fumei
11-04-2013, 09:58 PM
Better

jtukes
11-05-2013, 11:20 AM
Thanks guys, that worked!