我使用下面的代码为 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
最佳答案
您正在指定Range.Parent property在你的With ... End With statement但在最重要的时候却忽略了它。
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 object至Union不连续的单元格可能是以下之一。
.Range("K5, Z5")
Union(.Cells(5, "K"), .Cells(5, "Z"))
在上面的示例中,我将一个字符串连接在一起,就像这两个示例中的第一个示例一样。
1 参见Is the . in .Range necessary when defined by .Cells? 就这个主题进行认真的讨论。
关于vba - 为符合条件的非相邻单元格着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38341419/