PDA

View Full Version : VBA - Table Within a Table



GeorgeVince
03-04-2016, 02:14 PM
Hi,

I'm trying to create a table within a table using Word VBA, could anyone shed some light on how this is done programmatically?
I'm also trying to insert some text BEFORE the table.


Here's an example of what I'm trying to achieve (2a), I've managed to achieve 1a - any idea why the table inserted is 1x2 and not 2 x 2? and how to insert text before the table?

15558

Sub createTable()

Dim myRange As Range
Set myRange = ActiveDocument.Range(0, 0)
ActiveDocument.Tables.Add Range:=myRange, NumRows:=2, NumColumns:=2

Set myRange = ActiveDocument.Tables(1).Cell(2, 2).Range

ActiveDocument.Tables(1).Tables.Add Range:=myRange, NumRows:=2, NumColumns:=2

ActiveDocument.Tables(1).Tables(1).Borders.Enable = True
ActiveDocument.Tables(1).Borders.Enable = True


End Sub

gmaxey
03-04-2016, 04:21 PM
Sub createTable()

Dim myRange As Range
Set myRange = ActiveDocument.Range(0, 0)
ActiveDocument.Tables.Add Range:=myRange, NumRows:=2, NumColumns:=2

Set myRange = ActiveDocument.Tables(1).Cell(2, 2).Range
myRange.Collapse wdCollapseStart
myRange.InsertBefore "Test" & vbCr
myRange.Collapse wdCollapseEnd
ActiveDocument.Tables(1).Tables.Add Range:=myRange, NumRows:=2, NumColumns:=2

ActiveDocument.Tables(1).Tables(1).Borders.Enable = True
ActiveDocument.Tables(1).Borders.Enable = True


End Sub

gmayor
03-05-2016, 12:51 AM
You might find it simpler to keep track if you name your tables e.g.

Sub createTable()
Dim oTable1 As Table
Dim oTable2 As Table
Dim myRange As Range

Set myRange = ActiveDocument.Range(0, 0)
Set oTable1 = ActiveDocument.Tables.Add(Range:=myRange, NumRows:=2, NumColumns:=2)
Set myRange = ActiveDocument.Tables(1).Cell(2, 2).Range
myRange.Collapse wdCollapseStart
myRange.InsertBefore "Test" & vbCr
myRange.Collapse wdCollapseEnd
Set oTable2 = ActiveDocument.Tables.Add(Range:=myRange, NumRows:=2, NumColumns:=2)
oTable2.Borders.Enable = True
oTable1.Borders.Enable = True
End Sub

GeorgeVince
03-06-2016, 09:53 AM
Wow - Appreciate the help guys!