如果我有一个循环开始:
For each c in Range("A1:C8")
占位符c (c.count, c.value, c.something,...)
的属性是否标识了循环到目前为止迭代的次数?我宁愿使用这样的东西而不是包含另一个变量。
答案 0 :(得分: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
是一个计数器,但也用于识别受代码影响的单元格。
答案 1 :(得分: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)
答案 2 :(得分: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