2017-10-19 65 views
0

我有檢查輸入的日期與當前的日期,並填寫細胞在適當的顏色,並檢查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)'來檢查單元格是否爲空 –

回答

0

可能是一些與您的數據,它可以正常運行了我。你在F欄中有什麼樣的數據?

+0

f列包含日期 –

+0

這不提供問題的答案。一旦你有足夠的[聲譽](https://stackoverflow.com/help/whats-reputation),你將可以[對任何帖子發表評論](https://stackoverflow.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

1

如果單元格中有非日期值,則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