根据日期和其他条件突出显示单元格

时间:2013-03-27 22:14:39

标签: excel vba excel-vba conditional highlight

我正在尝试在VBA中根据特定条件编写突出显示功能。我可以通过条件格式轻松地做到这一点,但我注意到,如果用户剪切/粘贴(除了特殊)/删除行/等。然后修改条件格式范围。我希望条件格式范围保持固定而不是映射到实际单元格。如果有人知道如何做,或保护条件格式但仍然允许数据操作,那么这段代码是不必要的。

我找到了两个不同的代码,但是因为我是VBA的新手,所以我不是很擅长并遇到问题。我不知道如何使用Isblank或Isempty功能。

我需要以红色突出显示早于30天的日期(包括已过去的日期)。我需要突出显示早于60天的日期,但是黄色的日期超过30天。没有数据的细胞和超过60天的细胞必须保持不变。

非常感谢任何帮助!

Private Sub Worksheet_Change(ByVal Target As Range)

Dim icolor As Integer

    If Not Intersect(Target, Range("C3:T65")) Is Nothing Then

        Select Case Target

            Case Is <= Date + 60

                icolor = 6

            Case Is <= Date + 30

                icolor = 3

            Case IsEmpty()

                icolor = 2

        End Select


        Target.Interior.ColorIndex = icolor

    End If

End Sub

其他选择:

Sub Highlight()
    Dim cell As Range

    For Each cell In Range("C3:T65")
        If cell.Value <= Date + 60 And cell.Value > Date + 30 Then
            cell.Offset(0, 1).Interior.ColorIndex = 6

        ElseIf cell.Value <= Date + 30 Then
            cell.Offset(0, 1).Interior.ColorIndex = 3

        ElseIf cell.Value IsEmpty() Then
            cell.Offset(0, 1).Interior.ColorIndex = 2

        End If
    Next cell

End Sub

2 个答案:

答案 0 :(得分:0)

使用VBNullString检查单元格为空:

ElseIf cell.Value = vbNullString Then

答案 1 :(得分:0)

你的代码几乎都在那里。以下两者的组合应该可以完成这项工作:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim icolor As Integer
    Dim cell As Range

    If Intersect(Target, Range("C3:T65")) Is Nothing Then Exit Sub

    For Each cell In Target
        icolor = 0
        Select Case cell
            Case Is <= Date + 30: icolor = 3
            Case Is <= Date + 60: icolor = 6
            Case "": icolor = 2
        End Select
        If icolor <> 0 Then cell.Interior.ColorIndex = icolor
    Next cell
End Sub
相关问题