【问题标题】:Visual Basic Excel Color Cells on Lost Focus失去焦点的 Visual Basic Excel 颜色单元格
【发布时间】:2014-06-20 16:07:16
【问题描述】:

我需要在 excel 中制作一个 VBA 脚本,当一个单元格的值至少比另一个单元格大或小 10% 时,它会为 2 个单元格着色

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 语句为真之后也是如此。
我对 VBA 几乎一无所知,所以任何解释都会很棒。谢谢!

【问题讨论】:

  • Worksheet_Change2 不是有效的事件处理程序。
  • 将您的两个逻辑组合到Worksheet_Change 事件处理程序中。您需要这方面的帮助吗?
  • 我愿意。我对 VBA 几乎一无所知
  • 好的。原始的Worksheet_Change 事件是否如您所愿?
  • 不,这两个事件都不起作用。

标签: vba excel colors


【解决方案1】:

继续我上面的 cmets,让我们将逻辑组合到一个事件处理程序中。

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

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

修订和简化

 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

【讨论】:

  • 还是不行。我已经在线获得了 rgb 颜色并将其更改为该颜色,但即使有您的其他建议,它似乎也不起作用。
  • 这绝对有效。如果你愿意,我可以证明这一点。现在,它可能没有做您想要的事情,但它确实正在工作。请描述您所说的“它不起作用”是什么意思——没有发生的事情应该发生,或者正在发生的事情不应该发生,等等。
  • 当值太大或太小时,这两个单元格应该会改变颜色,但无论我将值设置为什么,它们都不会改变颜色。
  • 目前它们是什么颜色的?
  • 感谢所有帮助和处理我的无知!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-09
  • 2014-07-14
  • 1970-01-01
  • 1970-01-01
  • 2016-10-22
  • 1970-01-01
  • 2018-11-23
相关资源
最近更新 更多