使用dynamic颜色键的Excel vba条件格式

我试图创build一个Excelmacros,将条件格式应用到另一列中的单元格的条件和另一列(本质上是一个颜色键)中的单元格的格式的目标列。

颜色键是单列图表,每行中包含文本的彩色单元格(例如蓝色单元格为文本“蓝色”)。

目标是能够更改颜色键中的填充颜色或文本,并使目标单元格自动更改为新的颜色或条件,而无需通过Excel的条件格式规则pipe理器对新的RGB进行硬编码。

这样可以节省很多时间,因为有很多颜色,而且它们必须是精确的RGB匹配。

以下是我到目前为止:

Sub ColorCode() 'Applies conditional formatting to Input Chart using the Color Key Application.ScreenUpdating = False Dim ColorKey As Range Set ColorKey = Worksheets(2).Range("C6:C19") Dim kCell As Object Dim lCell As Object Dim mCell As Object With Worksheets(2) For Each mCell In Worksheets(2).Range("Input[Duration1]") If mCell.Value <> "0" Then For Each lCell In Worksheets(2).Range("Input[Color1]") If lCell.Value <> "" Then For Each kCell In ColorKey.Cells If lCell.Value = kCell.Value Then mCell.Interior.Color = kCell.Interior.Color mCell.Font.Color = kCell.Font.Color End If Next End If Next End If Next End With 

这遍历列中的每个单元格,并实际上将它们着色。问题是所有的单元格被着色到最后一个单元格的条件,所以所有的颜色是相同的,而不是每个单元格格式化为自己的条件。

在添加"application.screenupdating=false" ,我可以看到循环中的颜色闪烁,但它们不会粘住。 当我尝试添加"ByVal Target as Range"我的代码,我的macros消失,说实话,即使我已经看了这个我不明白这是什么意思。

我是VBA新手,很确定我错过了一些简单的东西。 我真的很感激任何帮助!

我把这个标记为答案 – 这里是更新的代码!

 Sub getcol() Dim rr As Range Dim tg As Range Set color_dict = CreateObject("Scripting.Dictionary" For Each rr In Range("colorkey") color_dict.Add rr.Text, rr.Interior.Color Next For Each rr In Range("input[color1]") rr.Offset(0, -2).Interior.Color = color_dict(rr.Text) Next End Sub 

不太了解规则,以确定目标单元格应该从您的描述颜色。

但是在任何情况下,您可能都希望创build一个dictionary来存储text键的颜色。 然后使用这个字典来遍历你的目标区域,并通过读取目标单元格中​​的文本来设置单元格的颜色(??)

在下面,我假设创build字典键的文本位于范围color_key旁边的列中。 如果您想要读入的文本创build字典键实际上是在同一列,然后删除offset (或将其设置为0列偏移量)。

我假设color_keytarget_Range在您的Excel表(某处)被命名的范围。

 Sub getcol() Dim rr As Range Set color_dict = CreateObject("Scripting.Dictionary") For Each rr In Range("color_key") color_dict.Add rr.Offset(0, 1).Text, rr.Interior.Color Next For Each rr In Range("target_Range") rr.Interior.Color = color_dict(rr.Text) Next End Sub 

代码CELL.Interior.Color返回一个代表单元格填充颜色的整数代码,正如你所提到的,你需要完全相同的颜色。

字典dict通过使用语法dict.Add key, value读取(键,值)对来工作。 并通过相应的键时返回值: dict(key)=value