简体   繁体   中英

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?

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 . 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. A counter is, indeed, the only way that "always" works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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