简体   繁体   English

我可以在没有计数器的情况下引用“ for each”循环的索引吗?

[英]Can i reference the index of a “for each” loop without a counter?

I am wondering if there is an index attribute for the object of a for each loop. 我想知道是否每个循环的对象都有一个索引属性。

The simple answer is to include a counter variable within the for each loop, independent from the loop itself (as i have done with the i variable in the code) and create the index as you go, but i'm wondering if there is a way of getting the index directly from the loop construct? 简单的答案是在for每个循环中包括一个计数器变量,独立于循环本身(如我在代码中对i变量所做的那样)并随您创建索引,但是我想知道是否存在一个直接从循环构造中获取索引的方法?

i = 1
For Each cell In rRange
    MsgBox cell.Index???
    MsgBox i

    i = i + 1
Next cell

Obviously, in the case of the code i have provided index is not an attribute I can use. 显然,在代码中我提供的索引不是我可以使用的属性。 Is there an attribute there which would work like this? 那里有可以像这样工作的属性吗?

The general answer is, no, VBA does not provide a way to ascertain the "index" of the loop it's in while executing For Each . 普遍的答案是,不,VBA没有提供一种在执行For Each确定其所在循环的“索引”的方法。 You might be able to calculate it, as is suggested in a comment, depending on what the object is. 如注释中所建议的那样,您可能能够计算出它,具体取决于对象是什么。 But there's nothing inherent in VBA that can do this for you. 但是VBA并没有内在的功能可以为您做到这一点。 A counter is, indeed, the only way that "always" works. 实际上,计数器是“始终”起作用的唯一方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM