需要帮助将表格放在页面的开头

时间:2019-07-01 16:32:15

标签: vb.net ms-word

我将表格放入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编码,而且我对选择对象的复杂性了解甚少,所以我确定这就是我的问题所在。如果有人可以向我展示完成我想要做的一个好方法,我将不胜感激。

预先感谢

Darren

1 个答案:

答案 0 :(得分:-1)

尝试以下代码。确保表的行数允许它适合一页。如果这样做不起作用,请尝试在表格中少排一行,Word可能需要在表格前后添加一些空格,具体取决于活动格式。

Selection.EndKey Unit:=wdStory
ActiveDocument.Tables.Add Selection.Range, 5, 5
Selection.EndKey Unit:=wdStory
Selection.InsertBreak WdBreakType.wdPageBreak
Selection.EndKey Unit:=wdStory
ActiveDocument.Tables.Add Selection.Range, 5, 5
' ...

当然,这只是向您展示一种行之有效的方法,可以避免您遇到的困难。您需要使代码适应您的特定任务。