按照单元格颜色显示行的颜色代码

时间:2013-12-31 14:52:28

标签: vba excel-vba excel

我只是想知道是否可以使用VBA代码根据彩色单元格填充行颜色。

例如

enter image description here

我希望第4行与B4颜色相同。我使用以下代码,但它不起作用。我想我需要做点其他事情,请提出建议。

Sub Color1()

Dim lastR as Long, 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") = Rows(i).Interior.Color = RGB(255, 255, 0) Then
 Rows(i).Interior.Color = RGB(255, 255, 0)
End if

Next i

End Sub

1 个答案:

答案 0 :(得分:1)

以下应该这样做(为sheet1添加WITH):

Sub Color1()

Dim lastR As Long, i As Long

With Sheets("Sheet1")

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

    For i = lastR To 2 Step -1

        If .Cells(i, "B").Interior.Pattern = xlNone Then
            .Rows(i).Interior.Pattern = xlNone
        Else
            .Rows(i).Interior.Color = .Cells(i, "B").Interior.Color
        End If

    Next i

End With

End Sub