Arrays 将Word文档中的所有表移动到文档末尾

Arrays 将Word文档中的所有表移动到文档末尾,arrays,vba,indexing,dynamic,static,Arrays,Vba,Indexing,Dynamic,Static,我想把所有表格移到文件的末尾,只是为了在单独的会议中首先处理所有其他非表格(普通)段落。这就是我(最终)提出的代码: Dim iCounter As Integer For iCounter = 1 To ThisDocument.Tables.Count ThisDocument.Tables(1).Range.Select Selection.Cut Selection.EndKey (wdStory) Selection.TypeParagraph

我想把所有表格移到文件的末尾,只是为了在单独的会议中首先处理所有其他非表格(普通)段落。这就是我(最终)提出的代码:

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
上面的解决方案是一个看似正常的循环,结果是不相关的,并以不间断运行结束。我不得不强行关闭文字窗口。以及:

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

上面的解决方案,另一个看似正常的循环,在试运行时,输出一个“半成品”,即它移动一些表,而不是所有表。

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

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

您的第三个示例与此类似:您正在从选择中删除某些内容,然后将其放置在选择的末尾—这是一种奇怪的行为。在本例中,还将增加表号。因此,如果
表(1)
移到末尾,并且
表(2)
变成
表(1)
,当您将
计数器
增加到
表(2)
时,您实际上是在处理最初的
表(3)
[现在的
表(2)
]而新的
表(1)
[以前的
表(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