Excel奇数行给予价值

我正在尝试为特定列/范围中的所有奇数单元赋值。 到目前为止,我有下面的代码从另一个问题,但它不是工作:

Sub changeClass() Dim r As Range Set r = Range("B16").End(xlDown) 'set the range the data resides in For i = 1 To r.Rows.Count 'merge step If i Mod 2 = 1 Then 'this checkes to see if i is odd r.Cells.Value = "value" End If Else r.Cells.Value = "value2" Next i End Sub 

基本上我需要它为单元格16列中的每一个单元格的值添加一个值,直到最后一个单元格在有数据的列中。在偶数行上,值将是一件事,在奇数上它将是另一个。

非常感谢!

尝试一下,我相信这是行不通的,因为你不是在循环中的每个单独的单元格。 在下面的macros中,我使用'rng'来表示单元格的整个范围,'r'表示循环的每个增量中的单个单元格。

 Sub changeClass() Dim rng As Range Dim r As Range Set rng = Range(Cells(16,2),Cells(16,2).End(xlDown)) For i = 1 To rng.Rows.Count Set r = rng.Cells(i) If i Mod 2 = 1 Then ' You may want to test if it is odd based on the row number (depends on your problem...) r.Value = "Odd Value" Else r.Value = "Even Value" End If Next i End Sub 
 Sub changeClass() Dim r As Range Dim i As Integer For Each r In Range("B16:B24") 'Change this range i = r.Row If i Mod 2 = 1 Then 'this checks to see if i is odd r.Cells.Value = "ODD" Else r.Cells.Value = "EVEN" End If Next r End Sub 

你已经搞砸了你的陈述,不要closures它,否则closures它只有完全完成它! ;) 这里:

 Sub changeClass() Dim r As Range Set r = Range("B16").End(xlDown) 'set the range the data resides in For i = 1 To r.Rows.Count 'merge step If i Mod 2 = 1 Then 'this checkes to see if i is odd r.Cells.Value = "value" Else r.Cells.Value = "value2" End if Next i End Sub 

你不需要这样的循环:

 Sub OddRowAlert() With Range("B16:B100") .Formula = "=IF((MOD(ROW(B16),2)),""Odd"",""Even"")" .Formula = .Value End With End Sub 

只需在公式中用你想要的来代替奇数和偶数