Vba 需要对象。内饰。颜色

Vba 需要对象。内饰。颜色,vba,Vba,我是一个vba noob,所以请对我放轻松,我正在尝试循环通过一个数组,并替换范围背景色,如果它匹配绿色 然而,我的代码中出现了一个对象必需的错误,我试图弄明白为什么会出现这种情况,我知道在使用interior.color时应该有一个对象引用,但不使用 设置loop\u target=loop\u over.interior.color到底是这个颜色?我只是不明白出了什么问题。。。谢谢 Sub change_color() Dim loop_over As Variant Dim loop_t

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

然而,我的代码中出现了一个对象必需的错误,我试图弄明白为什么会出现这种情况,我知道在使用interior.color时应该有一个对象引用,但不使用 设置loop\u target=loop\u 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

您可以对范围内的每个单元格使用
,并使用
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

您正在使用颜色设置范围(循环目标)(loop_over.interior.color您应该将
Set
放在
loop_over=…
前面,就像您稍后对另一个变量所做的那样。对象需要Set语法。也不确定您为什么要将颜色指定给某个范围。我从设置loop_over开始,但我在循环的开头得到了一个类型不匹配(对于I=1),在这种情况下,我如何执行循环?我之所以将集合置于颜色上,是因为我想在我循环时使用循环\目标。哦,您试图将范围作为数组而不是范围读取(基于您的循环。当您在设计时知道它将是什么类型时,我不喜欢变量类型。但是如果您想要一个数组,您不需要
设置
是正确的,但我认为您需要放置
()
在上面的
Dim loop\u over
之后。你们把我引向了正确的方向。我现在将代码修改为。
code
子更改颜色()Dim loop\u over As Range Dim loop\u target()As Variant Dim I As Long Dim j As Long Dim color\u Range As Long Set loop\u over=Range(“B4:L22”)loop_target=loop_over.Interior.Color表示i=1到UBound(loop_target,1)表示j=1到UBound(loop_target,2)如果loop_target是RGB(0,128,0),则loop_target=“RGB(255,0,0)”Next j Next i End Sub
code
我更喜欢在设计时声明End类型。但是告诉我,循环目标应该是什么类型?谢谢。我会更深入地研究这段代码。但是如果将其放入数组中,执行时间不是更快吗?我注意到您只将rng作为范围,因此rng不是array?我认为如果区域是数组,则只能在区域中循环。如果您只想访问某个区域中的值,并且该区域很大,则将值加载到数组中并在该数组上循环绝对是一种方法。但是,在这里,您对值不感兴趣(因为您需要能够检查填充颜色),所以您需要直接使用该系列。非常感谢!也谢谢您。这是一个快速的方法。
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