You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否无需计数器直接引用For Each循环的索引?

Can You Get an Index Directly from a VBA For Each Loop?

Great question—this is a common point of confusion with VBA's For Each structure! Let's clear this up:

First, the straight answer: No, VBA's native For Each loop doesn't include a built-in way to grab the current iteration index (like the manual i counter you're using). The Index property you tried doesn't exist for Range objects in this context, and most iterable objects in VBA don't expose a direct "loop position" property through For Each.

That said, depending on what you're working with, there are alternatives to either get positional info or simplify the process:

1. For Range Objects: Absolute or Relative Position

If you're looping through a range (like your rRange example), you can get absolute row/column numbers directly from the cell object:

For Each cell In rRange
    ' Get the cell's absolute row number in the worksheet
    MsgBox "Absolute Row: " & cell.Row
    ' Get the cell's absolute column number
    MsgBox "Absolute Column: " & cell.Column
Next cell

If you need a relative index within your target range (e.g., "this is the 2nd cell in rRange"), you still need a counter—but you can keep it clean:

Dim i As Long
i = 1
For Each cell In rRange
    MsgBox "Relative Index: " & i
    i = i + 1
Next cell

Alternatively, if you prefer working directly with indexes, swap For Each for a For Next loop:

Dim i As Long
For i = 1 To rRange.Cells.Count
    MsgBox "Index: " & i
    MsgBox "Cell Value: " & rRange.Cells(i).Value
Next i

2. For Other Objects (Collections, Arrays)

  • Collections: No built-in index property here either. Stick with a manual counter, or use For Next with the collection's Count property to iterate by index.
  • Arrays: While For Each works on arrays, if you need the index, a For Next loop is far more straightforward—you can access the index directly using LBound and UBound:
    Dim myArray As Variant
    myArray = Array("apple", "banana", "cherry")
    Dim i As Long
    For i = LBound(myArray) To UBound(myArray)
        MsgBox "Index: " & i & ", Value: " & myArray(i)
    Next i
    

Why For Each Lacks Built-In Indexes

VBA's For Each is designed for iterating over items without worrying about their position. It's optimized for cases where you just need to process each element, not track its sequence number. That's why the manual counter is the go-to workaround when you need that positional context.


内容的提问来源于stack exchange,提问作者John Owens

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:38:39