能否无需计数器直接引用For Each循环的索引?
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 Nextwith the collection'sCountproperty to iterate by index. - Arrays: While
For Eachworks on arrays, if you need the index, aFor Nextloop is far more straightforward—you can access the index directly usingLBoundandUBound: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

