颜色连续更高的细胞

时间:2017-10-26 13:41:23

标签: vba excel-vba excel

我正在尝试创建一个宏,该颜色的单元格高于前一个单元格。我想只为那些跟随5个细胞系列的细胞着色,每个细胞比前一个细胞更高。 在该屏幕截图中,如果我有这样的系列,则只有D14应该用红色着色,因为D14> D13> D12> D11> D10> D9。 换句话说,因为从D9到D13,5个单元总是高于前一个单元。

enter image description here

这是我的代码,但它不起作用:

Sub Consecutive_HigherCells()

Dim i, j As Integer

For j = 1 To 5

    If Cells (i,4).Value >> Cells(i-j,4).Value Then

    Cells(i, 4).Select

    With Selection.Font
        .Color = -16776961
        .TintAndShade = 0
    End With

    End If

Next j

End Sub

感谢您的帮助

2 个答案:

答案 0 :(得分:2)

显然,第一个候选人是 A6 (因为它有5个前辈)

Sub BetterRedThanDead()
    Dim i As Long, N As Long
    N = Cells(Rows.Count, "A").End(xlUp).Row
    For i = 6 To N
        If boo(Cells(i - 1, 1), Cells(i - 2, 1), Cells(i - 3, 1), Cells(i - 4, 1), Cells(i - 5, 1)) Then
            Cells(i, 1).Interior.ColorIndex = 3
        End If
    Next i
End Sub

Public Function boo(a, b, c, d, e) As Boolean
    boo = False
    If a > b And b > c And c > d And d > e Then boo = True
End Function

例如:

enter image description here

答案 1 :(得分:0)

您缺少声明i变量。 >>也不是比较值的正确方法。

行应该是:

If Cells (i,4).Value > Cells(i-j,4).Value Then

您还需要添加类似

的内容
If j = 5 Then 'It implies your validation is success
 With Selection.Font
        .Color = -16776961
        .TintAndShade = 0
    End With
End If