为VBA中的每个循环确定循环的迭代?

为VBA中的每个循环确定循环的迭代?,vba,excel,foreach,iteration,Vba,Excel,Foreach,Iteration,如果我有一个开始的循环: For each c in Range("A1:C8") 占位符c(c.count,c.value,c.something,…)是否有一个属性标识循环到目前为止的迭代次数?我宁愿使用这样的东西,也不要包含另一个变量。您需要像这样自己计算它 Dim i as integer i = 0 For each c in Range("A1:C8") i = i + 1 或 您可以这样做,而不是使用“范围内的每个c”: Dim c as Long 'presu

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

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

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

您需要像这样自己计算它

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

您可以这样做,而不是使用“范围内的每个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
Dim c as Long'假设您将其作为一个范围,只需将其更改为Long。
Dim myRange as Range“使用一个更易于稍后调用的范围变量
设置myRange=Range(“A1:C8”)
对于c=1到myRange.Cells.Count
'对单元格执行某些操作,将其标识为myRange.Cells(c),例如:
myRange.Cells(c).Font.Bold=True'(修订版)

根据迭代的方向,使用列或行属性,可以动态计算序号。因此

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

不。你必须自己计算。如果你的循环结构有点不同,就没有必要添加额外的变量来执行计算。您可以引用单元格范围,如
range(“A1:C8”)。只要
c
被标注为长/整数,单元格(c)
。如果对范围内的每个c使用
语法,则可以在循环内使用
c.Font.Bold=True
,因此,不需要
Long
变量……这种技术的问题是,它需要一个索引访问才能访问单元格范围,而单元格范围通常是迭代的wole点。@OlleSjögren如果OP希望能够在不使用额外计数器的情况下计算迭代次数,则需要
Long
变量变量。@DaleM不是每个c的
中每个迭代的
c
结果吗…
myRange.Cells(c)
相同吗?因此,对于OP的查询,有一种方法可以在不使用“额外”计数器变量的情况下执行他想要的操作。它可能不适用于所有情况,但根据我的经验,它适用于范围内的单元格、特殊单元格、数组中的项目、系列中的点、图表中的系列、窗体上的控件、工作表上的形状等。你能举一些例子说明这种方法不起作用的情况,以便OP能够确定解决问题的最佳方法吗?@DavidZemens OK,也许OP需要计数器来做其他事情,但在这个答案中,计数器唯一的用途是你不需要计数器的事情(当你在OP代码示例中已经有了
c
中的引用时,通过使用索引将字体设置为粗体)。我喜欢你的想法,但它不应该是myOrdinal=(c1.Row-1)*myRange.Columns.Count+c1.Column?作为一个老的C/C++程序员,我假设for-each循环首先遍历一行,然后遍历列,但您知道他们对假设的看法。如果首先是向下列,那么它将是myOrdinal=(c1.Column-1)*myRange.Rows.Count+c1.Row。。顺便问一下,是否可以指定for each循环遍历范围的方式,类似于.find函数(byRows或byColumns)?
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