自动更改单元格背景颜色Excel VBA [英] Automatically Changing Cell Background Colors Excel VBA

查看:274
本文介绍了自动更改单元格背景颜色Excel VBA的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So basically I want a code that can change color of cells. For example, if A1 = 1 and B1 = 3%, 54% or 5% then change B1's background color to green. Else if B1 = 1% or 2% change colors to red.

这是我到目前为止的内容,我似乎无法弄清楚.任何帮助将不胜感激.

This is what I have so far, I cant seem to figure it out. Any help will be greatly appreciated.

Sub color()
  Range("A1:B1").Formula = " = If(A1 = 1 AND B1 =3%,Range("A1:B1").Interior.ColorIndex = 4)"
End Sub

推荐答案

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

I think you can figure out how the code below works and make necessary changes



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

这篇关于自动更改单元格背景颜色Excel VBA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆