[英]Excel VBA - Change cell color based on value
请运行下一个代码。 它会自动将条件格式放在您需要的范围内:
Sub makeCondFormatting()
Dim sh As Worksheet, rng As Range, cond1 As FormatCondition, cond2 As FormatCondition
Set sh = ActiveSheet
Set rng = sh.Range("B76:K89")
With rng
.FormatConditions.Delete
Set cond1 = .FormatConditions.Add(xlExpression, Formula1:="=" & rng.cells(1, 1).Address(0, 0) & " <> """"")
Set cond2 = .FormatConditions.Add(xlExpression, Formula1:="=" & rng.cells(1, 1).Address(0, 0) & " = """"")
End With
With cond1
.Interior.color = RGB(255, 255, 255)
End With
With cond2
.Interior.color = RGB(197, 198, 198)
End With
End Sub
它将使范围单元格在单元格为空或不为空时自动更改其内部颜色。
试试这个代码
Sub SetColor()
Dim r As Range
Set r = ThisWorkbook.ActiveSheet.Range("B2:B7")
Dim white As Long
white = RGB(255, 255, 255)
Dim grey As Long
grey = RGB(200, 200, 200)
Dim c As Range
For Each c In r
If c.Value2 = 1 Then c.Interior.Color = white
If c.Value2 = 0 Then c.Interior.Color = grey
Next
End Sub
正如艾克提到的空值,你可以使用这个
Sub SetColor()
Dim r As Range
Set r = ThisWorkbook.ActiveSheet.Range("B2:B7")
Dim white As Long
white = RGB(255, 255, 255)
Dim grey As Long
grey = RGB(200, 200, 200)
Dim c As Range
For Each c In r
If IsEmpty(c.Value2) Then
c.Interior.Color = white
'OR
'c.Interior.Pattern = xlNone
Else
c.Interior.Color = grey
End If
Next
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.