【发布时间】:2017-07-20 03:41:04
【问题描述】:
我正在尝试创建一个 Excel 宏,它使用另一列中单元格的条件和另一列中单元格的格式(本质上是颜色键)将条件格式应用于目标列。
颜色键是单个柱形图,每行包含包含文本的彩色单元格(例如,带有“蓝色”作为文本的蓝色单元格)。
目标是能够更改颜色键中的填充颜色或文本,并让目标单元格自动更改为新的颜色或条件,而无需通过 Excel 的条件格式规则管理器对新的 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" 添加到我的代码中时,我的宏消失了,老实说,即使我查过这个,我也不是很明白这意味着什么。
我是 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
【问题讨论】:
-
不确定嵌套循环是否适合此处 - 您是否只想为与 mCell 位于同一行的单元格着色?
标签: excel vba dynamic conditional-formatting color-key