我使用下面的代码为列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
答案 0 :(得分:2)
您在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"))
在上面的示例中,我将一个字符串连接在一起,就像这两个例子中的第一个一样。
¹请参阅 Is the . in .Range necessary when defined by .Cells? ,就此主题进行认真讨论。
答案 1 :(得分:2)
你可以替换
Range(.Cells(i, 11), .Cells(i, 26)).Interior.ColorIndex = 6
与
.Cells(i, 11).Interior.ColorIndex = 6
.Cells(i, 26).Interior.ColorIndex = 6