【问题标题】:VBA to color row based on other column valuesVBA根据其他列值对行进行着色
【发布时间】:2014-07-14 14:50:40
【问题描述】:

我正在尝试根据 COL B、C、D 的行颜色为 A 列中的每一行着色。

说 A2 颜色是基于 B2,C2,D2 的颜色。如果其中任何一个为红色,则 A2 应为红色,否则 A2 为绿色

请在下面找到我的代码:

Option Explicit

Sub Sheet1()

Dim lastR As Long
Dim i As Long

lastR = Sheets("Sheet1").Cells(Rows.Count, "A").End(xlUp).Row

For i = lastR To 2 Step -1

    If ((Sheets("Sheet1").Cells(i, "B")) Or (Sheets("Sheet1").Cells(i, "C")) Or (Sheets("Sheet1").Cells(i, "D"))) = Rows(i).Interior.Color = RGB(255, 0, 0) Then
        Rows(i).Interior.Color = RGB(0, 255, 0)
    End If

Next i

End Sub

我的下标超出范围,错误代码 9。

这是我的 excel 屏幕打印:

【问题讨论】:

    标签: vba excel


    【解决方案1】:

    试试这个:

    Sub Sheet1()
        Dim rng As Range, cl As Range
    
        For Each cl In Worksheets("Sheet1").Range("A2:A" & Cells(Rows.Count, "A").End(xlUp).Row)
            If cl.Offset(0, 1).Interior.Color = 255 Or cl.Offset(0, 2).Interior.Color = 255 Or cl.Offset(0, 3).Interior.Color = 255 Then
                cl.Interior.Color = 255
            End If
        Next cl
    End Sub
    

    【讨论】:

      【解决方案2】:

      我认为问题出在lastR = Sheets("Sheet1").Cells(Rows.Count, "A").End(xlUp).Row

      Sheets("Sheet1").Cells(Rows.Count, "A") 会找到最后一个单元格,然后.End(xlUp) 会将所选内容再次带到第一行。

      当您说For i = lastR To 2 Step -1 时,您可能希望以-1 步从第一行转到第二行。这是不可能的。

      【讨论】:

        【解决方案3】:

        将单元格引用更改为如下所示(B 列的示例):

        Cells(i, 2)
        

        如果您要使用Range(),您可以使用您尝试过的样式,但您需要将值连接到“A1”样式单元格引用中,如下所示:

        Range("B" & i)
        

        【讨论】:

          猜你喜欢
          • 2017-07-25
          • 1970-01-01
          • 2012-09-23
          • 1970-01-01
          • 2014-05-07
          • 2015-11-26
          • 1970-01-01
          • 2021-09-03
          • 2016-12-30
          相关资源
          最近更新 更多