对于每个循环的反向顺序 [英] Reverse order of For Each loop

查看:129
本文介绍了对于每个循环的反向顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于VB的最强大的事情之一是能够循环遍历一个集合中的对象,而不用引用每个循环的索引

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使用迭代器)(否则需要一个偏移量,因为每次移动枚举器指针返回到先前的对象,一旦活动的对象被删除)

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)

eg。

For intA = 10 to 1 step -1 
    ' ...
Next

当使用For Each | Next
eg。

What about when using a For Each | Next eg.

For each rngCell in Selection.Cells
    ' ...
Next

如何循环向后使用对于每个循环语法?

How could I loop backwards using the for each loop syntax?

推荐答案

使用For x = a To b Step -1 for a collection of cells:

An alternative using "For x = a To b Step -1" for a collection of cells:

Sub reverseForEach()
    Dim lngCounter As Long, rng As Range

    Set rng = ActiveSheet.Range("A1:B5")

    For lngCounter = rng.Cells.Count To 1 Step -1

        Debug.Print rng(lngCounter).Address
        'rng(lngCounter) is shorthand for rng.item(lngCounter)

    Next lngCounter
End Sub

这应该适用于具有.item属性的大多数集合。

This should work with most collections that have the .item property.

这篇关于对于每个循环的反向顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆