颜色与相邻条件匹配的非相邻单元格

我使用下面的代码来对K和Z列中匹配条件的单元格着色; 但它为K和Z之间的所有单元格着色。要修复,我使用最后一行代码来删除L到Y列中的颜色。有没有办法将以“Range”开头的代码行修改为仅为单元格着色K和Z是否符合标准?

Sub ColrCls() Dim ws As Worksheet Dim lRow As Long, i As Long Set ws = ThisWorkbook.Sheets("Sheet1") With ws lRow = .Range("K" & .Rows.Count).End(xlUp).Row For i = 2 To lRow If .Cells(i, 11).Value = "Non Sen" And .Cells(i, 26).Value = "N/A" Then Range(.Cells(i, 11), .Cells(i, 26)).Interior.ColorIndex = 6 End If Next i Columns("L:Y").Interior.ColorIndex = xlNone End With End Sub 

您在With … End With语句中指定了Range.Parent属性 ,但在最重要时忽略它。

 Sub ColrCls() Dim ws As Worksheet Dim lRow As Long, i As Long Set ws = ThisWorkbook.Sheets("Sheet1") With ws lRow = .Range("K" & .Rows.Count).End(xlUp).Row For i = 2 To lRow If .Cells(i, 11).Value = "Non Sen" And .Cells(i, 26).Value = "N/A" Then .Range("K" & i & ", Z" & i).Interior.ColorIndex = 6 Else .Range("K" & i & ", Z" & i).Interior.Pattern = xlNone End If Next i End With End Sub 

联合不连续单元格的Range对象可以是下列之一。

 .Range("K5, Z5") Union(.Cells(5, "K"), .Cells(5, "Z")) 

在上面的例子中,我将这两个例子中的第一个串联在一起。


¹ 请参阅 在.Cells中定义时需要。 对这个问题进行认真的讨论。

你可以replace

 Range(.Cells(i, 11), .Cells(i, 26)).Interior.ColorIndex = 6 

 .Cells(i, 11).Interior.ColorIndex = 6 .Cells(i, 26).Interior.ColorIndex = 6