vba - 如何使用VBA在word文档中的表格后设置光标

标签 vba ms-access ms-word cursor-position

我必须在没有模板的情况下在 Word 文档中创建报告。该报告由来自 MS Access 的记录组成 - 并且将有一些文本,然后是一个表格,根据记录数进行迭代(我将根据记录数使用 VBA 动态创建表格)。 我可以使用书签作为起点开始在 Word 文档中插入文本,然后添加表格并填充单元格。问题一旦填写表格后,如何将光标放在表格后的下一行以开始插入文本。 以下是我的代码,任何有一些提示或示例的人都会感激 - 谢谢!

    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

最佳答案

要到达表格后面的点(段落),请将表格的 Range 分配给 Range 对象,然后将其折叠到其终点:

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"

关于vba - 如何使用VBA在word文档中的表格后设置光标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54562864/

相关文章:

excel - 如果表列中没有数据则显示消息框的代码

c# - Visual Studio 安装程序项目中的其他设置

c# - 如何从 C# 将 SQL Server 数据库转换/导出到 MSAccess

wpf - 如何在 MS Access VBA 窗体中托管 WPF 控件?

python - 将 Microsoft Word 方程转换为 Latex

ms-word - Microsoft Word 2016 表格单元格中的条件格式

c# - 如何在我使用 C# 生成 Word2007 文档时将 "Page x of y"页脚添加到它

excel - Sub Excel VBA的可选范围

Excel更改日期格式

vba - 为什么在 VBA 中重新排序操作数会避免 "Run-time Error 6: Overflow"?