第二个IF语句中的错误在哪里?

我有VBA代码检查input的date与当前date,并填写适当的颜色单元格,并检查是否colomn “F”不是空的,它会着色的D,E,F列。

问题是,直到现在我有21条logging,但系统只是彩色19条logging,所以2列在F列中不是空的。

码:

Private Sub CommandButton1_Click() Dim i As Long 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 Cells(i, 3).Interior.Color = xlNone 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 = vbRed ElseIf (VBA.CDate(Cells(i, 3)) - VBA.Date()) >= 5 And (VBA.CDate(Cells(i, 3)) - VBA.Date()) <= 10 Then Cells(i, 3).Interior.Color = vbCyan Else Cells(i, 3).Interior.ColorIndex = xlNone End If ' your 2nd criteria to color the entire row if "F" is not empty If Trim(Range("F" & i).Value) <> "" Then Range("D" & i & ":F" & i).Interior.ColorIndex = 15 Next End Sub 

如果单元格中有非date值,则ElseIf语句将抛出Runtime Error 13 。 这是由于尝试将非date值转换为dateVBA.CDate(Cells(i, 3))

 Private Sub CommandButton1_Click() Dim i As Long With Worksheets("Sheet1") For i = Range("C" & .Rows.Count).End(xlUp).Row To 2 Step -1 'Range upto 5000, chnge this as per your requirment' If IsDate(Cells(i, 3)) Then Select Case VBA.CDate(.Cells(i, 3)) - VBA.Date() Case Is < 0 .Cells(i, 3).Interior.Color = vbGreen Case Is = 0 .Cells(i, 3).Interior.Color = vbYellow Case Is <= 4 .Cells(i, 3).Interior.Color = vbRed Case Is <= 10 .Cells(i, 3).Interior.Color = vbCyan Case Else .Cells(i, 3).Interior.ColorIndex = xlNone End Select Else .Cells(i, 3).Interior.ColorIndex = xlNone End If ' your 2nd criteria to color the entire row if "F" is not empty If Trim(.Range("F" & i).Value) <> "" Then .Range("D" & i & ":F" & i).Interior.ColorIndex = 15 Next End With End Sub 

可能是你的数据的东西,它运行正常。 你在F列有什么样的数据?