Search code examples
vbaautomationms-wordole

Word Automation - Text, then table, then more text


I need your help,

I am trying to have text, followed by a table then more text however, the current output is table, text, then more text.

The problem:

enter image description here

The desired output:

enter image description here

The code in question:

function test() {

    var wordApp = new ActiveXObject("Word.Application")

    var doc = wordApp.Documents.Add()

        var sel = wordApp.Selection

    sel.TypeText("Text Content1")

    doc.PageSetup.LeftMargin = CentimetersToPoints(0.75)
    doc.PageSetup.RightMargin = CentimetersToPoints(0.75)

    doc.Tables.Add(Range=doc.Range(0, 0), numrows=1, numcolumns=10)
    doc.Tables(1).Range.Font.Size = 9
    doc.Tables(1).Range.Font.Name = 'Arial'
    doc.Tables(1).Rows(1).Range.Font.Bold = true    

    doc.Tables(1).Cell(1,1).Range.Text = '#'
    doc.Tables(1).Cell(1,2).Range.Text = 'File Number'
    doc.Tables(1).Cell(1,3).Range.Text = 'Subject'
    doc.Tables(1).Cell(1,4).Range.Text = 'Branch'
    doc.Tables(1).Cell(1,5).Range.Text = 'Division'
    doc.Tables(1).Cell(1,6).Range.Text = 'Related Documents'
    doc.Tables(1).Cell(1,7).Range.Text = 'Current Status'
    doc.Tables(1).Cell(1,8).Range.Text = 'Assigned To'
    doc.Tables(1).Cell(1,9).Range.Text = 'Action Required'
    doc.Tables(1).Cell(1,10).Range.Text = 'Last Updated'

    doc.Tables(1).AutoFitBehavior(1)


    sel.TypeParagraph()
    sel.TypeText("Text Content2")

    wordApp.Visible = true

    wordApp.Activate()

    wordApp.WindowState = 1
}

Solution

  • You're explicitly inserting your table at Range(0,0) (the very beginning of the document), hence why it's appearing above both text paragraphs. Try:

    doc.Tables.Add(sel.Range, numrows=1, numcolumns=10)
    

    Then, after your AutoFit you'll probably need to do this:

    doc.Range(doc.Range.End-1).Select()
    sel.TypeParagraph()
    sel.TypeText("TextContent2")