如何将颜色格式条件应用于一系列单元格并突出显示与条件匹配的行?

问题描述 投票:0回答:1

我有一个命令按钮宏的代码(我在论坛中获得),它可以选择工作表中的各种单元格,并根据三个按钮状态中的每一个,以不同的颜色突出显示所选单元格的背景。

我稍微调整了代码:

Private Sub CommandButton1_Click()
Dim Nam As Variant
Static c
Nam = Array("A", "B", "C", vbYellow, vbCyan, vbWhite)
If c = 3 Or c = "" Then c = 0
CommandButton1.Caption = Nam(c)
CommandButton1.BackColor = Nam(c + 3)

Range("A:G").Interior.ColorIndex = xlNone
Select Case Nam(c)
    Case "A": Range("A1:U1000").Interior.ColorIndex = 6
    Case "B": Range("A1:U1000").Interior.ColorIndex = 8
    Case "C": Range("A1:U1000").Interior.ColorIndex = 0
End Select
c = c + 1
End Sub

但我需要对于每个按钮状态,它仅突出显示(在三个按钮状态的每种颜色中)选择块中包含特定单元格内的值的行,该单元格始终位于每行内的同一列中。

类似这样的:

如果按钮状态为 A,则单元格 Jn(J1、J2、J3...)内包含“y”的所有行都会以 A 设置的颜色突出显示。类似 If (Jn = "y ") 然后突出显示整行... n = n+ 1... 转到下一行... 重复...

如果按钮状态为 B,则单元格 Jn 内包含“n”的所有行都会以 B 设置的颜色突出显示

如果按钮状态为 C,则包含“y”或“n”的所有行将恢复为不填充其单元格...

excel vba if-statement range
1个回答
0
投票

在 Select 语句中,将 ColorIndex 分配给变量。然后循环遍历范围内的每一行并检查每一列 J 是否满足您的条件。如果是,请将 ColorIndex 应用于该行。

Private Sub CommandButton1_Click()
Dim Nam As Variant
Static c
Nam = Array("A", "B", "C", vbYellow, vbCyan, vbWhite)
If c = 3 Or c = "" Then c = 0
CommandButton1.Caption = Nam(c)
CommandButton1.BackColor = Nam(c + 3)

Range("A:G").Interior.ColorIndex = xlNone

Dim NewColor As Long
Select Case Nam(c)
    Case "A": NewColor = 6
    Case "B": NewColor = 8
    Case "C": NewColor = 0
End Select

Dim rg As Range
Dim i As Long
Set rg = Range("A1:U1000")
For i = 1 To rg.Rows.Count
    If Cells(i, "J") = "y" Then Range(Cells(i, "A"), Cells(i, "U")).Interior.ColorIndex = NewColor
Next i
c = c + 1
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.