比较date以填充适当的颜色

在Excel中使用VBA我有一个代码,将input的date与当前的date进行比较,并根据结果系统将以正确的颜色填充单元格。

代码在四种情况下比较。 如果input的date减去当前是:

  • = 0
  • 小于0
  • 在1和4之间
  • 在4和10之间

使用IF语句,但系统给我一个错误,错误在哪里以及如何解决?

码:

Private Sub CommandButton1_Click() Dim i As Integer For i = Range("C5000").End(xlUp).Row To 2 Step -1 'Range upto 5000, chnge this as per your requirment' If IsEmpty(Cells(i, 3)) Then Exit Sub ElseIf (VBA.CDate(Cells(i, 3)) - VBA.Date()) < 0 Then Cells(i, 3).Interior.Color = vbGreen ElseIf (VBA.CDate(Cells(i, 3)) - VBA.Date()) = 0 Then Cells(i, 3).Interior.Color = vbYellow ElseIf (VBA.CDate(Cells(i, 3)) - VBA.Date()) > 1 And (VBA.CDate(Cells(i, 3)) - VBA.Date()) < 4 Then Cells(i, 3).Interior.Color = vbBlue ElseIf (VBA.CDate(Cells(i, 3)) - VBA.Date()) > 4 And (VBA.CDate(Cells(i, 3)) - VBA.Date()) < 10 Then Cells(i, 3).Interior.Color = vbRed End If Next End Sub 

Exit Sub放在下一行。 或者甚至更好,删除该行代码,以便处理所有行,如…

 Private Sub CommandButton1_Click() Dim i As Integer For i = Range("C5000").End(xlUp).Row To 2 Step -1 'Range upto 5000, chnge this as per your requirment' If IsEmpty(Cells(i, 3)) Then ElseIf (VBA.CDate(Cells(i, 3)) - VBA.Date()) < 0 Then Cells(i, 3).Interior.Color = vbGreen ElseIf (VBA.CDate(Cells(i, 3)) - VBA.Date()) = 0 Then Cells(i, 3).Interior.Color = vbYellow ElseIf (VBA.CDate(Cells(i, 3)) - VBA.Date()) >= 1 And (VBA.CDate(Cells(i, 3)) - VBA.Date()) <= 4 Then Debug.Print VBA.CDate(Cells(i, 3)) - VBA.Date() Cells(i, 3).Interior.Color = vbBlue ElseIf (VBA.CDate(Cells(i, 3)) - VBA.Date()) > 4 And (VBA.CDate(Cells(i, 3)) - VBA.Date()) < 10 Then Debug.Print VBA.CDate(Cells(i, 3)) - VBA.Date() Cells(i, 3).Interior.Color = vbRed Else Cells(i, 3).Interior.Color = vbWhite End If Next End Sub