VBA - 基于特定单元格中的值更改单元格的颜色 [英] VBA-Change color of cells based on value in particular cell

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

问题描述

我想根据单元格 D2 的值更改单元格 A2:C2 的背景颜色。 / p>

这也适用于行3,4和5中的相对单元格。



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



如果它有所作为,目标范围( A2:D6 )将以表格格式。



我希望这个子程序执行打开工作簿我知道在哪里放这个子程序,所以不要汗水指示我如何。



我已经用条件格式化了,但是有一些VBA我可以将面食复制到未来的报告中。

解决方案

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

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

For i = 2 To 5
Set r1 =范围(D& i)
设置r2 =范围(A& i; C& i)
如果r1.Value = 1则r2.Interior.Color = vbRed
如果r1.Value = 2然后r2.Interior.Color = vbBlue
如果r1.Value = 3然后r2.Interior.Color = vbYellow
下一个i
结束子


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

This also applies to the relative cells in rows 3,4, and 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.

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

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.

解决方案

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

这篇关于VBA - 基于特定单元格中的值更改单元格的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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