在excel文件中,我需要根据"是"的数量对列单元格进行颜色编码。在那个专栏中。如果没有"是" : 红色;一个"是":黄色:2或超过2"是":绿色。
这可以通过某些宏来完成吗?
更新:
已经制作了这个宏但我无法运行或调试它,因为它给出了溢出错误; 即使我已将其赋值为0,变量N的值也为32676。
Sub testcolor()
Dim i As Integer
Dim j As Integer
Dim N As Integer
Dim z As Integer
Dim val As String
i = 7
j = 5
N = 0
MsgBox (N)
For j = 5 To 15
Do While i < 13
val = ActiveSheet.Cells(i, j).Value
If val = "Yes" Then N = N + 1
Loop
If N = 0 Then
Range(i + 2, j).Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 255
.TintAndShade = 0
.PatternTintAndShade = 0
End With
End If
If N = 1 Then
Range(i + 2, j).Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
.PatternTintAndShade = 0
End With
End If
If N > 1 Then
Range(i + 2, j).Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 5296274
.TintAndShade = 0
.PatternTintAndShade = 0
End With
End If
Next j
End Sub
答案 0 :(得分:2)
解决此问题的另一种方法是使用条件格式。
=AND(E14="Yes",COUNTIF(E:E,"Yes")>=2,ROW()>=7,ROW()<=13)
=AND(E14="Yes",COUNTIF(E:E,"Yes")<2;COUNTIF(E:E,"Yes")>0,ROW()>=7,ROW()<=13)
=AND(E14="Yes",COUNTIF(E:E,"Yes")=0,ROW()>=7,ROW()<=13)
请勿忘记应用格式条件(绿色/黄色/红色背景)。
让我为你打破绿色公式:
您可以随时根据需要更改这些参数。也许比跳入大量代码更容易。使用带有多个条件的条件格式可能看起来很困难,但是一旦你掌握了它,你就不会停止使用它。
答案 1 :(得分:1)
试试这个(相应地设置RGB和ColorIndex,如果你想要单元格文本颜色或填充颜色,则没有得到):
Sub ConditionalColorColumn()
count = Application.WorksheetFunction.CountIf(arg1:=Range("D:D"), arg2:="yes")
'MsgBox count
If count = 1 Then
ActiveSheet.Range("D:D").Font.Color = RGB(255, 255, 0)
ActiveSheet.Range("D:D").Interior.ColorIndex = 6
ElseIf count >= 2 Then
ActiveSheet.Range("D:D").Font.Color = RGB(255, 255, 0)
ActiveSheet.Range("D:D").Interior.ColorIndex = 6
Else
ActiveSheet.Range("D:D").Font.Color = RGB(255, 255, 0)
ActiveSheet.Range("D:D").Interior.ColorIndex = 6
End If
End Sub
附录:你可以尝试多列
Sub ConditionalColorMultiColumn()
'Dim arr As Variant
'Dim desCell As Range
arr = Array("E", "F", "G", "H", "I","J","K")
For i = 0 To UBound(arr)
Set rngg = Range(arr(i) & 7 & ":" & arr(i) & 12)
'rngg.Select
Set desCell = Cells(14, arr(i))
Count = Application.WorksheetFunction.CountIf(arg1:=rngg, arg2:="yes")
'MsgBox count
If Count = 1 Then
desCell.Interior.ColorIndex = 6
ElseIf Count >= 2 Then
desCell.Interior.ColorIndex = 4
Else: desCell.Interior.ColorIndex = 3
End If
Set desCell = Nothing
Set rngg = Nothing
Next
End Sub