简体   繁体   English

当单元格值由于另一个宏而改变时执行宏

[英]execute macro when cell value changes due to another macro

I have a sheet with two buttons. 我有一张有两个按钮的床单。 One button places a value in a cell (E2) and the other button counts that value (in E2) down by 1 every time it is pushed. 一个按钮在单元格(E2)中放置一个值,每次按下该按钮时,另一个按钮(在E2中)将该值向下计数1。 I want the value in E2 cell to dictate the color of D2, such that D2 is Red whenever the value of the cell is > 0 and green when it is =< 0. 我希望E2单元格中的值决定D2的颜色,以便每当该单元格的值> 0时D2为红色,而当其值= <0时D2为绿色。

Here are my two buttons: 这是我的两个按钮:

Button 1 按钮1

Sub Use2()
     Range("e2").Value = Range("d2")
End Sub

Button 2 按钮2

Sub Subtract1()
     Range("E2").Value = Range("E2").Value - 1
End Sub

I added this code: 我添加了以下代码:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address = Range("E2").Address and Target.Value >0 Then
      Range("D2").Interior.Color = vbRed
  End If
End Sub

I didn't even get to the green part because this only works if I manually enter a value greater than 0 in E2. 我什至没有进入绿色部分,因为这仅在我在E2中手动输入大于0的值时才有效。 It doesn't work if the value of E2 changes to a value > 0 by pushing button 1. Can anyone help me change this so it works. 如果通过按按钮1将E2的值更改为大于0的值,则此方法不起作用。 Thanks! 谢谢!

Whenever using Worksheet_Change event 每当使用Worksheet_Change事件

1) Use Application.EnableEvents to prevent Events from firing when other code is running. 1)使用Application.EnableEvents防止事件在其他代码运行时触发。

2) Use Error Handling so that EnableEvents is set to True 2)使用错误处理,以便将EnableEvents设置为True

Private Sub Worksheet_Change(ByVal Target As Range)
    Application.EnableEvents = False

    On Error Resume Next

    If Not Intersect(Range("E2"), Target) Is Nothing Then

        If Target.Value > 0 Then
            Range("D2").Interior.Color = vbRed
        Else
            Range("D2").Interior.Color = vbGreen
        End If
    End If

    Application.EnableEvents = True
End Sub

It can also be achieved using Conditional Formatting. 也可以使用条件格式来实现。

在此处输入图片说明

In addition to @Santosh's comments about Enable/Disable Events during runtime of event macros, assuming your subroutines are all in the Worksheet code module, you can simply force a call to the _Change event like so: 除了@Santosh关于在事件宏运行期间启用/禁用事件的注释之外,假设您的子例程都在Worksheet代码模块中,则可以像下面这样简单地强制调用_Change事件:

Sub Use2()
    Range("E2").Value = Range("E2")
    Worksheet_Change Range("E2")
End Sub

Sub Subtract1()
    Range("E2").Value = Range("E2").Value - 1
    Worksheet_Change Range("E2")
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM