2015-10-30 80 views
-1

我一直在尋找類似的主題,但無法找到適合我的問題的解決方案。條件格式行VBA

目標:
我有一個excel表格中,我把關於我的工作的研究數據: -company,工作職位,申請發送日期,......,最後幾天的應用程序之間傳遞的數日期和今天的日期。

我想要一個宏來檢查每個位置等待的天數(列I中的值)並有條件地將顏色應用於整個行。這樣我可以對我的工作調查進行良好的跟蹤。

代碼使用

Sub outofdate() 
Range("I4").Select 
Range(Selection, Selection.End(xlDown)).Select 
numrow = Selection.Rows.Count 

For r = 4 To numrow 
    c = Cells(r, 9).Value 
    Select Case c 
      Case Is = 7 < c < 10 
      ColorIndex = 4 
      Case Is = 10 < c < 15 
      ColorIndex = 45 
      Case Is = 15 < c < 21 
      ColorIndex = 3 

    End Select 'c 

    With Range(Cells(r, 1), Cells(r, 9)).Select 
     Selection.Interior.Color = ColorIndex 
    End With 
Next 
End Sub 

面臨的問題
當我運行宏,從範圍A4單元格:I12都有色黑色的,即使我不把顏色索引指黑色。

感謝您的時間,我一直在努力弄清楚哪裏出了問題,但我的知識似乎停在這裏。

+3

你沒有VBA實現容易嗎? – pnuts

+0

以下關於@pnuts註釋 - 選擇您的範圍,然後選擇功能區上的主頁,然後選擇條件格式。有幾種選項可以創建格式,即使是公式選項。 –

+1

我不確定你爲什麼想用VBA來做到這一點,難道你不能輕易地用Excel中的條件格式化選項構建它嗎? – BasDeBeer

回答

0

的問題是,如果用於黑色的代碼是零,你的顏色變量是永遠不會從零更改,因此它會給你黑色。此外,「選擇案例」的符號工作不正常。

Sample for Select Case

Option Explicit 

Sub outofdate() 

    Dim rWorkRange As Range 
    Dim r As Range 
    Dim lColorIndex As Long 
    Dim lValue As Long 

    ' Set the range for the loop. 
    Set rWorkRange = Range(Range("I4"), Range("I4").End(xlDown)) 

    ' Loop through the range. 
    For Each r In rWorkRange 

     lValue = r.Value 

     ' Select each case, make sure that the else sets the 
     ' lColorIndex variable to the default "0" 
     Select Case lValue 
      Case 7 To 10 
       lColorIndex = 4 
      Case 10 To 15 
       lColorIndex = 45 
      Case 15 To 21 
       lColorIndex = 3 
      Case Else 
       lColorIndex = 0 
     End Select 

     ' Check for the "0" value (This is the black color) 
     ' if the lColorIndex is zero then skip. 
     If Not lColorIndex = 0 Then 
      Cells(r.Row, 1).Resize(, 9).Interior.ColorIndex = lColorIndex 
     End If 
    Next r 

End Sub 

希望這有助於:)

+0

確實它幫助了很多!謝謝 !我現在明白了邏輯,唯一沒有得到的點是「lValue = r.Value」 –

+0

「lValue = r.Value」用於獲取循環中單元格的值 – newjenn

+0

你是對的,我我將這個值放在一個變量的範圍內以便以後檢查。 –

0

我已經使用if和else if而不是選擇的情況下

Sub outofdate() 


    Dim numrow As Long 

    numrow = ActiveSheet.Range("I" & Rows.Count).End(xlUp).Row 

    For r = 4 To numrow 
    c = Cells(r, 9).Value 


    If c > 7 And c < 10 Then 

     Cells(r, 9).EntireRow.Interior.ColorIndex = 4 

    ElseIf c > 10 And c < 15 Then 

      Cells(r, 9).EntireRow.Interior.ColorIndex = 45 

    ElseIf c > 15 And c < 21 Then 

     Cells(r, 9).EntireRow.Interior.ColorIndex = 3 

    End If 

    Next 

    End Sub 
+0

的確如此,但它只是突出了單元格而不是整條線。 –

+0

@ M.O - 簡單的修復,只需將以'.ColorIndex'結尾的行改爲'Cells(r,9).EntireRow.Interior.ColorIndex'(添加'EntireRow'位)。然後它會突出整個行! – BruceWayne

+0

@BruceWayne謝謝。我已經對解決方案進行了修改。 – newjenn