Andy Wang
Andy Wang

Reputation: 11

How to create separate tables in VBA word?

I am trying to create two separate tables in VBA

I've checked a lot of threads, but can't figure it out. Keep getting an error. I am able to create the first table, or create a second table nested in the first one, but is unable to create two separate tables.

Dim objWord
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
Set oDoc = objWord.Documents.Add
Set oTable = oDoc.Tables.Add(oDoc.Range(0, 0), 6, 4)

oDoc.Paragraphs.Add
Set aRange = ActiveDocument.Paragraphs.Last.Range

Set oTable2 = oDoc.Tables.Add(oDoc.aRange, 5, 4)

oTable.Borders.Enable = True
oTable2.Borders.Enable = True

The line Set oTable2 = oDoc.Tables.Add(oDoc.aRange, 5, 4) gets an error. I am not sure what to do about the aRange that was declared earlier.

Upvotes: 1

Views: 473

Answers (1)

macropod
macropod

Reputation: 13505

Try:

Dim wdApp As Object, wdDoc As Object, wdTbl As Object
Set wdApp = CreateObject("Word.Application")
With wdApp
  .Visible = True
  Set wdDoc = .Documents.Add
  With wdDoc
    Set wdTbl = .Tables.Add(.Range.Characters.Last, 6, 4)
    wdTbl.Borders.Enable = True
    .Range.InsertAfter vbCr
    Set wdTbl = .Tables.Add(.Range.Characters.Last, 5, 4)
    wdTbl.Borders.Enable = True
  End With
End With

Upvotes: 1

Related Questions