在 VBA 中识别 For Each 循环的迭代?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14886658/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 19:37:06  来源:igfitidea点击:

Identifying the iteration of a For Each loop in VBA?

vbaexcel-vbaforeachiterationexcel

提问by GrahamD

If I have a loop that commences:

如果我有一个开始的循环:

For each c in Range("A1:C8")

Is there a property of the placeholder c (c.count, c.value, c.something,...)that identifies the number of times the loop has iterated thus far? I would rather use something like this than including another variable.

是否有占位符的属性c (c.count, c.value, c.something,...)来标识迄今为止循环迭代的次数?我宁愿使用这样的东西而不是包含另一个变量。

回答by David Zemens

Instead of using a "for each c in range" you can do something like this:

您可以执行以下操作,而不是使用“对于范围内的每个 c”:

Dim c as Long 'presumably you did this as a Range, just change it to Long.
Dim myRange as Range 'Use a range variable which will be easier to call on later
Set myRange = Range("A1:C8")

For c = 1 to myRange.Cells.Count
    'Do something to the cell, identify it as myRange.Cells(c), for example:
    myRange.Cells(c).Font.Bold = True   '<--- replace with your code that affects the cell
Next

This allows you to do the exact same For/Next loop, without including an unnecessary counter variable. In this case, cis a counter but also serves the purpose of identifying the cell being impacted by the code.

这允许您执行完全相同的 For/Next 循环,而无需包含不必要的计数器变量。在这种情况下,c是一个计数器,但也用于识别受代码影响的单元格。

回答by Dale M

You need to count it yourself like this

你需要像这样自己数

Dim i as integer
i = 0    
For each c in Range("A1:C8")
    i = i + 1

Or

或者

Dim i as integer
Dim c as Range
For i = 0 to Range("A1:C8").Count - 1
    Set c = Range("A1:C8").Cells(i)

回答by K. Rhodes

(Revised)

(修改)

Using Column or Row properties, as appropriate to the direction you are iterating, you can compute an ordinal number on the fly. Thus

使用适合您迭代方向的 Column 或 Row 属性,您可以即时计算序数。因此

For Each c1 in myRange
    myOrdinal = c1.row - myRange.row + 1       ' down contiguous cells in one column
    myOrdinal = c1.Column - myRange.Column + 1 ' contiguous columns, L2R
Next