自动更改单元格背景颜色Excel VBA

时间:2017-04-20 18:31:32

标签: excel vba colors cells

所以基本上我想要一个可以改变细胞颜色的代码。 例如,如果A1 = 1且B1 = 3%,54%或5%,则将B1的背景颜色更改为绿色。否则,如果B1 = 1%或2%,则将颜色更改为红色。

这是我到目前为止所做的,我似乎无法弄明白。任何帮助将不胜感激。

子颜色() 范围(" A1:B1")。公式=" = If(A1 = 1 AND B1 = 3%,Range(" A1:B1")。Interior.ColorIndex = 4)"

End Sub

1 个答案:

答案 0 :(得分:0)

我认为您可以弄清楚下面的代码如何工作并进行必要的更改


Sub color()

  Dim ws As Worksheet
  Dim r As Range, c As Range
  Set ws = ThisWorkbook.ActiveSheet

  With ws
    Set r = Range("A1").CurrentRegion
  End With

  For Each c In r
    If c.Value = 1 And ((c.Offset(, 1) = 0.03) Or (c.Offset(, 1) = 0.54) Or (c.Offset(, 1) = 0.05)) Then
      Range(c, c.Offset(, 1)).Interior.ColorIndex = 4
    ElseIf c.Value = 1 And ((c.Offset(, 1) = 0.01) Or (c.Offset(, 1) = 0.02)) Then
      Range(c, c.Offset(, 1)).Interior.ColorIndex = 3
    End If
  Next

End Sub

相关问题