我在不同的单元格中有这样的值:
X G 43 71 19 T 13 Y 46
21 25 33 67 79 W 56 60 43
71 13 R 31 11 93 85 33 20
67 84 44 63 L 56 61 95 64
45 43 M 30 25 74 43 71 U
28 74 29 58 54 74 68 64 22
我要应用条件格式,当出现43后跟71,同时以黄色突出显示时,如果突出显示, 用红色表示该值块的以下5个“连续”单元格。如果不太复杂,可以用相同的颜色突出显示 43,71及以下5个单元格。
我尝试使用此公式进行条件格式设置,但不起作用。
=AND(A1="43",B1="71",C1:G1<>"")
我正在寻找的输出是这样的:
这可以通过vba完成吗?谢谢
答案 0 :(得分:2)
我觉得对公式进行处理会非常复杂。这是一种VBA替代方法(请注意,它不会在两次运行之间重置未受影响的单元格的填充颜色):
Option Explicit
Public Sub FormatCells()
Dim SourceRange As Range
Dim CurrentCell As Range
Dim LastCell As Range
Dim ColorExtras As Long
Set SourceRange = ActiveSheet.Range("A1:I6")
ColorExtras = 0
For Each CurrentCell In SourceRange
' Track if the extra five cells needs to be colored red ... using a countdown
If ColorExtras > 0 Then
CurrentCell.Interior.Color = rgbRed
ColorExtras = ColorExtras - 1
End If
' Check if the cell is 71 and the prior cell is 43 .. and if so, color both orange
If Not LastCell Is Nothing Then
If CurrentCell.Value = 71 And LastCell.Value2 = 43 Then
LastCell.Interior.Color = rgbOrange
CurrentCell.Interior.Color = rgbOrange
ColorExtras = 5
End If
End If
Set LastCell = CurrentCell
Next
End Sub
输出:
答案 1 :(得分:1)
尝试,执行时间似乎更快。
Sub test()
Dim vDB() As Range
Dim rngDB As Range
Dim rng As Range, rngU As Range
Dim blYes As Boolean
Dim i As Long, n As Long
Dim s, e
s = Timer
Set rngDB = Range("a1", "i6")
rngDB.Interior.Color = xlNone
For Each rng In rngDB
n = n + 1
ReDim Preserve vDB(1 To n)
Set vDB(n) = rng
Next rng
For i = 1 To n - 5
If vDB(i) = 43 And vDB(i + 1) = 71 Then
blYes = True
Set rngU = Nothing
For j = 2 To 6
If vDB(i + j) = "" Then
blYes = False
Exit For
Else
If rngU Is Nothing Then
Set rngU = vDB(i + j)
Else
Set rngU = Union(vDB(i + j), rngU)
End If
End If
Next j
If blYes Then
Union(vDB(i), vDB(i + 1)).Interior.Color = RGB(250, 237, 125)
rngU.Interior.Color = RGB(255, 203, 203)
End If
End If
Next i
e = Timer
MsgBox e - s
End Sub