简体   繁体   中英

Text after table in Word using VBA codes

I create a Word document using VBA codes and transfer data from Excel to a table I create in the Word document.

I get an error starting a new line/paragraph after the table.

My code selects the whole table but does not start new text after the table, so later content is being added to cell(1,1) in the table.

I am just showing you the structure of my codes and I get an error at the Selection.Collapse line of code.

run time error 438, object doesn't support this property or method.

Sub Word_Report()
    Dim objWord As Object
    Dim objDoc As Object
    Set objWord = CreateObject("Word.Application")
    objWord.Visible = True
    Set objDoc = objWord.Documents.Add()
    With objWord.Selection
        Set myTable = objDoc.Tables.Add(Range:=objWord.Selection.Range, NumRows:=7, NumColumns:=3)
        myTable.Borders.Enable = True

        ''' my table contents'''
    end with

    'start new line after table
    objDoc.Range.InsertAfter Chr(13) & "Hello"
    .Font.Size = 11
    .BoldRun

End sub

在此处输入图片说明

Edited

Try the following:

   Sub Word_Report()
    Dim objWord As Object
    Dim objDoc As Object
    Set objWord = CreateObject("Word.Application")
    objWord.Visible = True
    Set objDoc = objWord.Documents.Add()




     With objWord.Selection
    Set myTable = objDoc.Tables.Add(Range:=objWord.Selection.Range, NumRows:=7, NumColumns:=3)
      myTable.Borders.Enable = True

    ''' my table contents'''
    End With

    'start new line after table
    objDoc.Range.InsertAfter Chr(13) & "Hello"

    End Sub

Use .Range instead of Selection

To insert text immediately following at table, you have to set the range to the table then collapse the range . Insert your table, flow all your data into it, format the table.

When you've got it how you want it, use code like this where h1 is a Word.Range and objTemplate is a Word.Document object:

Set h1 = objTemplate.Tables(TableNum).Range

h1.Collapse Direction:=wdCollapseEnd

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM