【发布时间】:2019-07-01 16:32:15
【问题描述】:
我正在将表格放入 Word 文档中。表中的行数可能会有所不同,但行高是固定的,因此我知道可以容纳在单个页面上的最大行数。当我达到该最大数量时,我想在文档中添加一个新页面,然后在其上插入一个新表格。听起来很简单,但我遇到了各种奇怪的结果。 结果 #1:我尝试使用“Selection.InsertNewPage”和“Selection.InsertBreak(wdPageBreak)”。当我这样做时,添加了 2 页而不是 1 页。
NumberOfPages = SectionObject.Range.Information(wdNumberOfPagesInDocument)
TableLocation = TableObject.Range 'get the range object of the current table
TableLocation.Collapse(WdCollapseDirection.wdCollapseEnd) 'go to end of table
TableLocation.Select()
WordDocument.Application.Selection.InsertBreak(WdBreakType.wdPageBreak) 'adds 2 pages instead of 1
NumberOfPagesNew = SectionObject.Range.Information(wdNumberOfPagesInDocument)
为了尝试完成这项工作,我编写了这段代码(它不起作用)
If NumberOfPagesNew > NumberOfPages + 1 Then
TableLocation = WordDocument.Range.GoTo(wdGoToPage, wdGoToAbsolute, NumberOfPagesNew) 'go to last page of doc
TableLocation.Delete() 'delete that page
TableLocation = WordDocument.Range.GoTo(wdGoToPage, wdGoToAbsolute, NumberOfPagesNew - 1) 'go to new last page
TableLocation.Collapse(WdCollapseDirection.wdCollapseStart) 'move cursor to start of page
End If
'I add a new table using this code
TableObject = WordDocument.Tables.Add(TableLocation, NumberOfRowsNeeded - 1, 5)
但不是将我的表格放在最后一页,而是添加了另一个页面并将我的表格放在上面。最终结果是一个带有表格的页面、一个空白页面,然后是另一个带有表格的页面。
结果 #2:我尝试的另一件事是将光标移动到表格的末尾,添加一个换行符,然后将表格放在后面。这解决了我添加 2 页而不是 1 页的问题。但是,它在新页面上添加了 2 行而不是 1 行,这会抛出我的行计数代码。下面是我使用的代码。
TableLocation = TableObject.Range 'get range object of current table
TableLocation.Collapse(wdCollapseEnd) 'go to end of table
TableLocation.Select()
WordDocument.Application.Selection.InsertBreak(wdLineBreak) 'should add 1 line
TableLocation = WordDocument.Application.Selection.GoToNext(wdGoToLine)
TableLocation.Collapse(WdCollapseDirection.wdCollapseStart)
'I add my next table using this code.
TableObject = WordDocument.Tables.Add(TableLocation, NumberOfRowsNeeded - 1, 5)
此代码将我的表格放置在比应有位置低一行的位置。
我不会做很多 Word 编码,而且我对选择对象的复杂性知之甚少,所以我确信这就是我的问题所在。如果有人可以向我展示完成我想做的事情的好方法,我将不胜感激。
提前致谢,
达伦
【问题讨论】:
-
在 UI 中试试这个:在第一个表格之后插入第二个表格(您需要在它们之间留一个空段落!)单击第二个表格的第一个单元格,转到主页中的段落对话框启动器功能区的选项卡,对话框中的第二个选项卡(换行符和分页符)并激活选项以开始新页面。 (我使用的是移动设备,因此无法给出更准确的说明。)这是否满足您的需求?
-
Cindy,我正在通过代码完成所有这些工作。用户界面永远不会打开。
-
我明白这一点。我的建议是看看这种方法是否适合你。如果是这样,它可以在代码中实现。但在 UI 中工作时发现最佳方法要简单得多。