Search code examples
vbams-accessms-wordcursor-position

How to set cursor after a table in word document using VBA


I've to create a report in Word document without a template. This report consists of records from MS Access - and there will be some text and then a table, iterative based on # of records (I'll be creating tables dynamically using VBA based on the # of records). I can start inserting text in the word document using a bookmark as starting point and then able to add a table and fill in cells. The question once done filling in the table how can I place the cursor on the next line after table to start inserting text. following is my code anyone with some hints or example would appreciate - Thanks!

    Set wordObj = CreateObject("Word.Application")

    Set wordDoc = wordObj.Documents.Open(fileName:=wrdTMPLT, Visible:=True)

    wordDoc.Bookmarks("rptdate").Range.Text = Format(DATE, "dd-mmm-yyyy")
    Set wordrange = wordDoc.GoTo(what:=wdGoToBookmark, Name:="startpoint")      'set cursor to start point

    wordrange.Text = Me.Text3_CHK

    Set wordrange = wordDoc.GoTo(what:=wdGoToBookmark, Name:="tblpoint")      'set cursor to location to insert table

    Set tbl = wordDoc.Tables.Add(Range:=wordrange, numrows:=4, numcolumns:=2)

    tbl.CELL(1, 1).Merge MergeTo:=tbl.CELL(1, 2)
    tbl.CELL(3, 1).Merge MergeTo:=tbl.CELL(3, 2)
    tbl.CELL(4, 1).Merge MergeTo:=tbl.CELL(4, 2)

    tbl.CELL(1, 1).Range.InsertAfter "Title: "
    tbl.CELL(2, 1).Range.InsertAfter "Coordinator: "
    tbl.CELL(2, 2).Range.InsertAfter "Engineer: "
    tbl.CELL(3, 1).Range.InsertAfter "Vendor 1: "
    tbl.CELL(3, 2).Range.InsertAfter "Vendor 2: "
    tbl.CELL(4, 1).Range.InsertAfter "Contractor: "

    tbl.Borders.Enable = False

    'Following text to enter after the table above                       
    wordrange.Text = "HellO"

    'continue with next table ... n text/table cycle  based  # of records

Solution

  • To get to the point (paragraph) following a table, assign the table's Range to a Range object then collapse it to its end-point:

    Dim rng as Word.Range
    'Do things here until table is finished
    Set rng = tbl.Range
    rng.Collapse wdCollapseEnd
    'Now the Range is after the table, so do things with it, for example:
    rng.Text = "more text"