简体   繁体   English

使用基于选定单元格的单元格中的值更改选定单元格的颜色

[英]Change colour of selected cell using values in cells based off the selected cell

I have a macro to colour a cell based on the RGB values.我有一个宏可以根据 RGB 值为单元格着色。
I have cells A1, B1, and C1 for the RGB values.我有 RGB 值的单元格 A1、B1 和 C1。

Sub FillWithRBG()
    Range("D1").Interior.Color = RGB(Range("A1").Value, Range("B1").Value, Range("C1").Value)
End Sub

I can select anywhere in the worksheet, run the macro and only cell D1 will change colour.我可以选择工作表中的任何地方,运行宏,只有单元格 D1 会改变颜色。

I want to select cell D2, run the macro and Cell D2 changes colour based off values in A2, B2, and C2.我想选择单元格 D2,运行宏,然后单元格 D2 根据 A2、B2 和 C2 中的值更改颜色。

I imagine I need to set the active cell with a reference, then 1, 2 and 3 will be offset from the selected cell.我想我需要使用引用设置活动单元格,然后 1、2 和 3 将从所选单元格偏移。
An added bonus would be that the macro can only run in the D column to prevent errors.一个额外的好处是宏只能在 D 列中运行以防止错误。

This would be a simple approach这将是一个简单的方法

  • In the code Me.在代码Me. is refering to the current sheet指的是当前工作表

  • You have to place this code in the sheet's module您必须将此代码放在工作表的模块中

在此处输入图片说明

  • Columns in VBA are noted by numbers (so column A is referenced as column 1) VBA 中的列用数字表示(因此 A 列被称为第 1 列)

Code:代码:

Private Sub Worksheet_Change(ByVal Target As Range)
    
    
    ' Prevent change if changed values are no in these columns (1,2,3) numbers are equivalent to A, B, C
    If Target.Column > 3 Then Exit Sub
    
    ' Change color of D column (4 = D)
    Me.Cells(Target.Row, 4).Interior.Color = RGB(Me.Cells(Target.Row, 1).Value, Me.Cells(Target.Row, 2).Value, Me.Cells(Target.Row, 3).Value)
    
End Sub
  • If you want it to work only if you're changing one cell at a time add these lines:如果您希望它仅在一次更改一个单元格时工作,请添加以下行:

     ' Prevent change when more than one cell is changed If Target.Cells.Count > 1 Then Exit Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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