设置行中单元格范围内的背景颜色(不使用条件格式)

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

复制粘贴代码是糟糕的编码样式,但是我需要一个快速的解决方案。我想更改一行(不是列)中一些单元格的单元格背景色。我已经写了几行代码(在我复制和粘贴的代码下面),但是不确定我做错了什么。最终,我希望循环正常工作,以便以后可以在不同范围的数字上检查单元格的值。

If Range("C5").Value = 0 Then Range("C5").Interior.Color = XlRgbColor.rgbRed
If Range("D5").Value = 0 Then Range("D5").Interior.Color = XlRgbColor.rgbRed
If Range("E5").Value = 0 Then Range("E5").Interior.Color = XlRgbColor.rgbRed
If Range("F5").Value = 0 Then Range("F5").Interior.Color = XlRgbColor.rgbRed

If Range("C8").Value = 0 Then Range("C8").Interior.Color = XlRgbColor.rgbRed
If Range("D8").Value = 0 Then Range("D8").Interior.Color = XlRgbColor.rgbRed
If Range("E8").Value = 0 Then Range("E8").Interior.Color = XlRgbColor.rgbRed
If Range("F8").Value = 0 Then Range("F8").Interior.Color = XlRgbColor.rgbRed

*****我会喜欢使用的代码*****

  'Set myRange = Range("C5:F17")
    'Dim cell As Range
    'For Each cell In myRange.Rows(1)
    'If cell.Value = 0 Then cell.Interior.Color = XlRgbColor.rgbRed
    'Next cell
    'If myRange.Rows(1).Value = 0 Then myRange.Interior.Color = XlRgbColor.rgbRed
    Application.ScreenUpdating = True
End Sub  
excel vba
2个回答
1
投票

添加.Cells使其成为myrange.Rows(1).Cells。原因是没有它,单元格是$ C $ 5:$ F $ 5的范围,您可以在Debug.Print cell.Address中看到它。


0
投票

需要-> myrange.Rows(1).Cells访问每个单独的单元格。

© www.soinside.com 2019 - 2024. All rights reserved.