Splitting a table into columns using VBA in Word

Hello everyone.
I have this table in a doc file and I get some data in a recordset from an access file using vba. I want to display these data in the table but I want to add columns inside this table first and then put the data in the cells. Every time I want a different number of columns (depending on the data I got). How can I add columns and rows in a table? Thank you very much.
LVL 2
pelbooksAsked:
Who is Participating?
 
GrahamSkanConnect With a Mentor RetiredCommented:
You could get the table width by adding the column widths, then average that space out between the columns:

Sub AddColumn()
    Dim tbl As Table
    Dim tblwidth As Single
    Dim col As Column
   
    Set tbl = ActiveDocument.Tables(1)
   
    For Each col In tbl.Columns
        tblwidth = tblwidth + col.width
    Next col
   
    tbl.Columns.Add

    For Each col In tbl.Columns
        col.width = tblwidth / tbl.Columns.Count
    Next col
End Sub
0
 
GrahamSkanRetiredCommented:
If you already have your table in an object variable, then you can use these Subs:

Sub AddRow(tbl As Table)
Dim rowObject As Row
    Set rowObject = tbl.Rows.Add
End Sub

Sub AddColumn(tbl As Table)
    Dim colObject As Column
    Set colObject = tbl.Columns.Add
End Sub
0
 
pelbooksAuthor Commented:
Dear Graham Skan
how can I add my table as an object variable? Thank you.
0
Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

 
GrahamSkanRetiredCommented:
You will have to find it. Tables are indexed by their order in the document.

If it is the first, then you could do this

dim tbl as Table
tbl = doc.tables(1)
0
 
GrahamSkanRetiredCommented:
Sorry. Missed the Set.

dim tbl as Table
Set tbl = doc.tables(1)
0
 
pelbooksAuthor Commented:
Hello again!
This works indeed but the columns go outside the predefined maximum width! Can't I create the columns without going over the maximum width? Thank you.
0
 
pelbooksAuthor Commented:
great thanks a lot :)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.