2016-07-01 77 views
0

我正在編寫代碼,以便當單元格的值具有特定值時,它突出顯示該行(列G-O,但不是整行)的範圍。下面的代碼正確地識別「c」的值,但對隨機行進行着色。例如,當第2行(O2)的值低於40時,它會對第4行進行着色。請幫助!Excel VBA:基於單元值的顏色範圍

Sub color() 

    Dim lastrow As Long 
    Dim c As Variant 

    lastrow = Range("o" & Rows.Count).End(xlUp).Row 
    For Each c In Range("O1:O" & lastrow) 
     If c.Value < 40 Then 
      ' MsgBox (c) 
      Range(Cells(c, 7), Cells(c, 15)).Interior.ColorIndex = 7 
     End If 
    Next c 

End Sub 
+3

條件格式化將在不需要VBA的情況下執行此操作。你有想在VBA中做到這一點的原因嗎? –

回答

3

查看下面的更改。它與你如何使用Cells()有關。你有它的方式,它將使用「c」的值,而不是行。

Sub color() 

Dim lastrow As Long 
Dim c As Variant 
lastrow = Range("o" & Rows.Count).End(xlUp).Row 
    For Each c In Range("O1:O" & lastrow) 
     If c.Value < 40 Then 
      ' MsgBox (c) 
      Range(Cells(c.Row, 7), Cells(c.Row, 15)).Interior.ColorIndex = 7 
     End If 
    Next c 

End Sub 
+0

非常感謝,現在讓我感覺很好! – spaindc