2017-10-10 77 views
1

在Excel中使用VBA我有一個代碼,比較輸入的日期和當前的日期,並根據結果系統將以正確的顏色填充單元格。比較日期之間,以填補適當的顏色

其中代碼比較在四個條件。 如果輸入的日期減去的電流爲:

  • = 0
  • 小於0
  • 4和10

使用IF語句,但在間 1和4之間

  • 系統給我一個錯誤,錯誤在哪裏以及如何解決?

    代碼:

    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 
    
  • +1

    爲什麼要使用VBA?條件格式可以做這種事情。無論如何,如果你有錯誤 - 請更具體。什麼行會拋出錯誤?什麼錯誤信息? –

    +0

    我試圖使用條件格式化,但它沒有工作,因爲我想 –

    回答

    1

    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 
    
    +0

    你解決了我的錯誤謝謝你。 但現在我有一個問題,要麼如果結果是1和4之間或更多的顏色將是藍色的。 –

    +0

    我調整了我的答案,現在你應該得到所有的顏色。如果日期差異超過10天,則單元格顏色將變爲白色。 –