2014-06-20 86 views
0

我需要做一个VBA脚本在Excel中哪些颜色2个细胞,当一个值至少为10%,大于或小于其他Visual Basic中的Excel颜色单元

Private Sub Worksheet_Change(ByVal Target As Range) 
Application.EnableEvents = False 
If Target.Address = aprx_Lns Then 
If aprx_Lns > aprx2_Lns * 0.1 Then 
aprx_Lns.Interior.Color = Hex(FFFF00) 
aprx2_Lns.Interior.Color = Hex(FFFF00) 
ElseIf aprx_Lns < aprx2_Lns * 0.1 Then 
aprx_Lns.Interior.Color = Hex(FFFF00) 
aprx2_Lns.Interior.Color = Hex(FFFF00) 
End If 
End If 
Application.EnableEvents = True 
End Sub 
Private Sub Worksheet_Change2(ByVal Target As Range) 
Application.EnableEvents = False 
If Target.Address = aprx2_Lns Then 
If aprx_Lns > aprx2_Lns * 0.1 Then 
aprx_Lns.Interior.Color = Hex(FFFF00) 
aprx2_Lns.Interior.Color = Hex(FFFF00) 
ElseIf aprx_Lns < aprx2_Lns * 0.1 Then 
aprx_Lns.Interior.Color = Hex(FFFF00) 
aprx2_Lns.Interior.Color = Hex(FFFF00) 
End If 
End If 
Application.EnableEvents = True 
End Sub 

我是什么做错了?即使在使if语句的值为true之后,两个单元格都不会将颜色更改为所选颜色。
我对VBA几乎一无所知,所以任何解释都会很棒。谢谢!

+0

'Worksheet_Change2'是** **不是一个有效的事件处理程序。 –

+0

将两个逻辑组合到'Worksheet_Change'事件处理程序中。你需要帮助吗? –

+0

我是。我几乎不了解VBA –

回答

0

继续我上面的评论,让我们将逻辑结合到单个事件处理程序中。

此外,使用命名的范围/单元格很好,但您需要正确引用它们。在VBA中名称本身没有意义,除非它被限定为明确的范围。以Range("aprx_Lns")等字符串的形式传递名称

注意注意此代码仅在您直接更改这两个单元格中的一个的值时触发。这意味着如果这些单元格包含引用其他单元格的公式,并且其他单元格发生更改,则不会发生突出显示。

经修订的&简化

Private Sub Worksheet_Change(ByVal Target As Range) 
Dim aprx_Lns As Range 
Dim aprx_Lns2 As Range 
Dim difference As Double 
Dim diffRatio As Double 

Set aprx_Lns = Range("aprx_Lns") '## Modify as needed 
Set aprx2_Lns = Range("aprx2_Lns") '## Modify as needed 

Application.EnableEvents = False 
If Target.Address = aprx_Lns.Address Or Target.Address = aprx2_Lns.Address Then 


    difference = Abs(aprx_Lns)/Abs(aprx2_Lns) 
    '## compute the absolute difference as a ratio 
    diffRatio = Abs(1 - difference) 

    If diffRatio >= 0.1 Then 
    '### if the cell values differ by +/- 10%, then highlight them 
     aprx_Lns.Interior.Color = 65535 'vbYellow 
     aprx2_Lns.Interior.Color = 65535 'vbYellow 
    Else 
    '### otherwise, unhighlight them: 
     aprx_Lns.Interior.Color = xlNone 
     aprx2_Lns.Interior.Color = xlNone 
    End If 
End If 
Application.EnableEvents = True 

End Sub 
+0

它仍然无法正常工作。我已经在网上获得了rgb的颜色,并将其改为这样,但即使有其他建议,它似乎也没有工作。 –

+0

这绝对是工作。如果你愿意,我可以证明这一点。现在,它可能不会做你想要的东西*,但它*是*当然是在工作。请描述你的意思是“它不工作” - 发生的事情不会发生,或者发生的事情不应该发生,等等。 –

+0

当值太大或太大时,两个单元应该改变颜色或太小了,但他们根本不会改变颜色,不管我设定什么值。 –