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

我正在尝试在VBA中编写基于特定条件的高亮function。 我可以很容易地通过条件格式来做到这一点,但我注意到,如果用户剪切/粘贴(非特殊)/删除行/等。 那么条件格式化范围将被修改。 我希望条件格式范围保持固定,而不是映射到实际的单元格。 如果有人知道如何做,或保护条件格式,但仍然允许数据操作,那么这个代码将是不必要的。

我发现了两个不同的代码,我一直在尝试,但由于我是VBA新手,我不是很擅长,遇到问题。 我不知道如何使用Isblank或Isemptyfunction。

我需要突出显示从现在起30天之前(包括通过date)的date。 我需要突出显示从现在开始的60天之前的date,但是以黄色显示30天以上的date。 没有数据和细胞超过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 

你的代码几乎都在那里。 以下两者的组合应该做这个工作:

 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 

使用VBNullString检查单元格是否为空:

 ElseIf cell.Value = vbNullString Then