5

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

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

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

4

3 回答 3

4

您可以执行以下操作,而不是使用“for each c in range”:

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

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

于 2013-02-15T04:10:33.843 回答
1

你需要像这样自己数

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

或者

Dim i as integer
Dim c as Range
For i = 0 to Range("A1:C8").Count - 1
    Set c = Range("A1:C8").Cells(i)
于 2013-02-15T04:03:22.703 回答
0

(修改)

使用 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
于 2013-08-07T04:23:05.243 回答