Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating tables in MS Word using VBA

Tags:

ms-word

vba

What are the codes to create a table in MS Word?

I've used the record function for macro to see how it is written and i have no idea how to interpret this.

and can you not draw tables while recording a macro? It greys out the "draw table" function.

I need to make a talbe that has some merged cells within the table - it would be easier if i can draw the table and record using macro but it seems like i can't do that...

table

I've used the draw function to draw the follow table but i can't record it.

HELP?!

like image 873
Doolie1106 Avatar asked Dec 12 '22 20:12

Doolie1106


2 Answers

This should get you started.

Sub Tester()


    Dim x, w, c

    ThisDocument.Tables(1).Delete

    ThisDocument.Tables.Add Range:=Selection.Range, NumRows:=7, NumColumns:=1, _
                          DefaultTableBehavior:=wdWord9TableBehavior, _
                          AutoFitBehavior:=wdAutoFitFixed

    With ThisDocument.Tables(1)

        .Rows.Height = 70
        w = .Rows(1).Cells(1).Width

        .Rows(1).Cells(1).Split 1, 7
        .Rows(1).Cells(1).Width = w / 2
        For x = 2 To 7
            .Rows(1).Cells(x).Width = (w / 2) / 6
        Next x

        .Rows(5).Height = 15
        .Rows(7).Height = 15

        .Rows(7).Cells(1).Split 1, 7

        .Rows(6).Cells(1).Split 1, 4
        .Rows(6).Cells(2).Split 2, 1

        'Once you merge cells it gets difficult to use .Rows, but
        '  you can still address individual cells. Use the loop below to
        '  find out which one you need to operate on...
        x = 1
        For Each c In .Range.Cells
            c.Range.Text = x
            x = x + 1
        Next c

        .Range.Cells(16).Split 1, 4
        'you can figure out setting the exact required widths...
    End With
End Sub
like image 71
Tim Williams Avatar answered Dec 31 '22 22:12

Tim Williams


the basic command for making a table is

ActiveDocument.Tables.Add Range:=Selection.Range, NumRows:=4, NumColumns:= 3

and to split/merge cells:

Selection.Cells.Split NumRows:=1, NumColumns:=2
Selection.Cells.Merge
like image 39
SeanC Avatar answered Dec 31 '22 22:12

SeanC