简体   繁体   English

使用VBA代码在Word中表格后的文本

[英]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. 我使用VBA代码创建Word文档,并将数据从Excel传输到在Word文档中创建的表中。

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. 我的代码选择整个表,但不会在表后开始新文本,因此以后的内容将添加到表中的cell(1,1)。

I am just showing you the structure of my codes and I get an error at the Selection.Collapse line of code. 我只是向您展示代码的结构,并且在代码的Selection.Collapse行出现错误。

run time error 438, object doesn't support this property or method. 运行时错误438,对象不支持此属性或方法。

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 使用.Range而不是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: 获得所需的代码后,请使用如下代码,其中h1Word.RangeobjTemplateWord.Document对象:

Set h1 = objTemplate.Tables(TableNum).Range

h1.Collapse Direction:=wdCollapseEnd

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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