问题描述
VB 最强大的功能之一是能够在不引用索引的情况下遍历集合中的对象 - for each
循环.
One of the most powerful things about VB is ability to loop through objects in a collection WITHOUT referring to the index - for each
loop.
我发现只想从集合中删除对象非常有用.
I find it very useful only want to remove objects from a collection.
从预定义的对象(例如电子表格上的行)中删除对象时,如果我使用索引并从最大的开始并返回到第一个,则代码会更简单.(使用迭代器的步骤 -1)(否则需要一个偏移量,因为一旦活动对象被删除,For each 会将枚举器指针移回前一个对象)
When doing removing objects from a predefined such as rows on a spread sheet the code is simpler if I use indexing and start at the largest and work back to the first. (Step -1 with an iterator) (otherwise requires an offset as the For each moves the enumerator pointer back to the previous object once the active one is deleted)
例如
For intA = 10 to 1 step -1
' ...
Next
当使用 For Each 时怎么样?下一个例如.
What about when using a For Each | Nexteg.
For each rngCell in Selection.Cells
' ...
Next
如何使用 for each
循环语法向后循环?
How could I loop backwards using the for each
loop syntax?
推荐答案
使用 for each 循环语法无法向后循环.
It's not possible to loop backwards using the for each loop syntax.
作为替代方案,您可以使用 For i = a To 1 Step -1
循环:
As an alternative you can use a For i = a To 1 Step -1
loop:
Sub reverseForEach()
Dim i As Long, rng As Range
Set rng = ActiveSheet.Range("A1:B2")
For i = rng.Cells.Count To 1 Step -1
Debug.Print rng.item(i).Address
' Or shorthand rng(i) as the Item property
' is the default property for the Range object.
' Prints: $B$2, $A$2, $B$1, $A$1
Next i
End Sub
这适用于所有具有 Item 属性的集合.例如工作表、区域或形状.
This works with all collections that have the Item property. For instance Worksheets, Areas or Shapes.
注意:在 Range 对象上使用时循环的顺序是从右到左,然后向上.
Note: The order of the loop when using on the Range object is from right to left, then up.
这篇关于For Each 循环的逆序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!