需要对象.Interior.Color

时间:2014-07-24 19:36:53

标签: vba

我是一个vba noob,所以对我很轻松,我正在尝试循环一个数组并替换范围背景颜色,如果它匹配绿色。

但是我的代码中出现了一个对象必需的错误,我想弄清楚的是为什么会发生这种情况,我知道在使用interior.color时我应该有一个对象引用但是没有使用 准确设置loop_target = loop_over.interior.color吗?我根本不明白出了什么问题......谢谢

Sub change_color()

Dim loop_over As Variant
Dim loop_target As Range
Dim i As Long
Dim j As Long
Dim color_range As Long

loop_over = Range("B4:L22")

For i = 1 To UBound(loop_over, 1)
    For j = 1 To UBound(loop_over, 2)
        Set loop_target = loop_over.Interior.Color
' If statement here -> If interior.color = green Then 
' new interior.color = red or something


    Next j
Next i

End Sub

2 个答案:

答案 0 :(得分:0)

Sub change_color()

Dim c as Range, rng As Range, clr as long

Set rng = ActiveSheet.Range("B4:L22")

    For i = 1 To rng.Rows.Count
        For j = 1 To rng.Columns.Count
            clr = rng.Cells(i,j).Interior.Color
            If clr = vbGreen Then
                rng.Cells(i,j).Interior.Color = vbRed
            End If
        Next j
    Next i

End Sub

答案 1 :(得分:0)

您可以使用范围中的For Each Cell并使用Cell.Interior.Color

来保持简单
Sub change_color()    
Set MyRng = Range("B4:L22")
  For Each Cell In MyRng.Cells
    Debug.Print Cell.Interior.Color & "-" & Cell.Value
    If (Cell.Interior.Color = 456752) Then Cell.Interior.Color = 1234567
  Next Cell

End Sub