哪里是错误在第二个IF语句

哪里是错误在第二个IF语句

问题描述:

我有检查输入的日期与当前的日期,并填写细胞在适当的颜色,并检查colomn “F”没有清空将色彩VBA代码D,E,F列。哪里是错误在第二个IF语句

问题是我到目前为止有21条记录,但系统只是彩色19条记录,所以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 
+0

为什么使用VBA?看起来像是'Conditional formatting'的工作。 –

+0

是的,我知道,但我想使用vba –

+0

代码看起来没问题。使用'debug.print len(Range(“F”&i).Value)'来检查单元格是否为空 –

可能是一些与您的数据,它可以正常运行了我。你在F栏中有什么样的数据?

+0

f列包含日期 –

+0

这不提供问题的答案。一旦你有足够的[声誉](https://*.com/help/whats-reputation),你将可以[对任何帖子发表评论](https://*.com/help/privileges/comment);相反,[提供不需要提问者澄清的答案](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-c​​an- I-DO-代替)。 - [来自评论](/ review/low-quality-posts/17673638) – Hannu

如果单元格中有非日期值,则ElseIf语句将抛出Runtime Error 13。这是由于尝试将非日期值转换为日期而造成的VBA.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