Excel奇数行给出值

时间:2013-03-26 13:36:08

标签: excel vba

我正在尝试为特定列/范围内的所有奇数单元格分配值。到目前为止,我从另一个问题中获取了以下代码,但它不起作用:

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

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

非常感谢!

4 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

试试这个,我相信它不起作用,因为你没有进入循环中的每个单独的单元格。在下面的宏中,我使用'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

答案 2 :(得分:0)

你搞砸了你的if语句,不要关闭它,否则只有在完成它之后关闭它! ;)这里:

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

答案 3 :(得分:0)

你不需要循环:

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

只需将公式中的奇数和偶数替换为您想要的