繁体   English   中英

Excel VBA - 根据值更改单元格颜色

[英]Excel VBA - Change cell color based on value

在指定范围内的表格中,我想将具有值的单元格标记为白色,将其他没有值的单元格标记为灰色。 我有代码,但它没有产生任何结果。 也没有错误。 要改变什么才能让它发挥作用

For Each cell In wbMe.Sheets("page3").Range("B76:K89")
If cell.Value = "Yes" Then cell.Interior.ColorIndex = 10
If cell.Value = "No" Then cell.Interior.ColorIndex = 3
   Next cell

在此处输入图像描述

运行下一个代码。 它会自动将条件格式放在您需要的范围内:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM