【问题标题】:Moving all the tables in a Word document to the end of the document将 Word 文档中的所有表格移动到文档末尾
【发布时间】:2018-07-05 18:01:42
【问题描述】:

我想将所有表格移到文档末尾,以便在单独的会话中首先处理所有其他非表格(普通)段落。这是我(最终)想出的代码:

Dim iCounter As Integer

For iCounter = 1 To ThisDocument.Tables.Count
    ThisDocument.Tables(1).Range.Select
    Selection.Cut
    Selection.EndKey (wdStory)
    Selection.TypeParagraph
    Selection.Paste
Next iCounter

它已经奏效了。但是,我想知道:为什么我总是要操作第一张桌子,而不是第一张,第二张……等等直到最后一张?这种“不断变化的指标”或“不变的地方应该改变”现象的总称或一般概念是什么?为什么像下面这样的普通循环不起作用?

for each oTable in ThisDocument.Tables
    oTable.Range.Cut
    Selection.EndKey (wdStory)
    Selection.TypeParagraph
    Selection.Paste
DoEvents
next oTable

上面的解决方案,一个看似正常的循环,结果不正确并最终不间断地运行。我不得不强制关闭 Word 窗口。并且:

Dim iCounter as Integer

For iCounter = 1 To ThisDocument.Tables.Count
    ThisDocument.Tables(iCounter).Range.Cut
    Selection.EndKey (wdStory)
    Selection.TypeParagraph
    Selection.Paste
Next iCounter

上述解决方案,另一个看似正常的循环,在试运行时,会输出一个“半成品”,即它移动了一些而不是全部的桌子。

【问题讨论】:

  • 索引是按位置移动的,所以当你移动第一个表时,下一个表会变成第一个?

标签: arrays vba indexing dynamic static


【解决方案1】:

对于您的第一个工作示例提出的原始问题 - 为什么总是选择 Table(1)?当你把表格剪下来放在文档末尾时,原来的Table(1) 变成了Table(n)Table(2) 现在变成了Table(1)。但它有效,因为您没有更改表的总数,因此循环准确地迭代了n 次。

在您的第二个示例中,您在遍历集合时从集合中删除一个对象。因为您随后将该对象放在集合的末尾,所以迭代永远不会到达末尾。 基本规则:永远不要在 For-Each 循环中删除或重新排序任何内容!

您的第三个示例类似:您正在从选择中删除某些内容,然后将其放在选择的末尾 - 奇怪的行为。在这种情况下,您还增加了表格编号。因此,如果Table(1) 移动到末尾,并且Table(2) 变为Table(1),当您将icounter 增加到2 时,您实际上是在处理最初的Table(3) [现在Table(2)] 和新的Table(1) [原为Table(2)] 保持不变。

当您知道要从集合或列表中删除某些内容时,避免这种混淆的最简单方法是向后工作。然后,您可以避免 (1) 而不是 (iCounter) 的细微编码。

Dim iCounter as Integer
Dim NumLoops as Long

NumLoops = ThisDocument.Tables.Count 
' NumLoops is not important in this example, but 
' when you delete (not move) a table you also change the overall count.

For iCounter = NumLoops To 1 Step -1    
    ThisDocument.Tables(iCounter).Range.Cut
    Selection.EndKey (wdStory)
    Selection.TypeParagraph
    Selection.Paste
Next iCounter

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-04
    • 2014-12-29
    • 1970-01-01
    • 2012-10-19
    • 2011-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多