VBA-根据特定单元格中的值更改单元格的颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35142985/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 10:12:17  来源:igfitidea点击:

VBA-Change color of cells based on value in particular cell

excelvbaexcel-vba

提问by Mark Romano

I want to change the background colors of cells A2:C2based on the value of cell D2.

我想A2:C2根据 cell 的值更改单元格的背景颜色D2

This also applies to the relative cells in rows 3,4, and 5.

这也适用于第 3、4 和 5 行中的相关单元格。

If the value in cell D#is 1, I'd like color x. If the value is 2, I'd like color y, if the value is 3, I'd like the color z.

如果单元格中的D#值为 1,我想要颜色 x。如果值为 2,我想要颜色 y,如果值为 3,我想要颜色 z。

If it makes a difference, the target range (A2:D6) will be in a table format.

如果有所不同,目标范围 ( A2:D6) 将采用表格格式。

I'd like this subroutine to execute upon opening the workbook. I know where to put that subroutine so don't sweat instructing me how.

我希望在打开工作簿时执行此子例程。我知道把那个子程序放在哪里,所以不要费力地指导我如何。

I've done this with conditional formatting, but it'd be nice to have some VBA I can copy-pasta into future reports.

我已经使用条件格式完成了这项工作,但是如果有一些 VBA 可以将面食复制到未来的报告中,那就太好了。

回答by Gary's Student

You should use Conditional formatting, but this works:

您应该使用条件格式,但这有效:

Sub ColorMeElmo()
   Dim i As Long, r1 As Range, r2 As Range

   For i = 2 To 5
      Set r1 = Range("D" & i)
      Set r2 = Range("A" & i & ":C" & i)
      If r1.Value = 1 Then r2.Interior.Color = vbRed
      If r1.Value = 2 Then r2.Interior.Color = vbBlue
      If r1.Value = 3 Then r2.Interior.Color = vbYellow
   Next i
End Sub