1

我正在尝试实现一个在满足特定条件时显示消息的代码。在这种情况下,它应该在Sheet2's A1's值等于或大于 1000 时发生。另一方面,该值由位于 中的公式定义Sheet1。我尝试实现基于此线程的解决方案:每次单元格获取值被公式更改时,如何运行 VBA 代码?

所以我得到了这个:

Private Sub Worksheet_Change(ByVal Target As Range)
Dim updatedCell As Range
Set updatedCell = Range("A1")

If Not Application.Intersect(updatedCell, Range("A:A")) Is Nothing Then
    If updatedCell.Value >= 1000 Then
        MsgBox "Something requires attention"
    End If
End If
End Sub

A1当我通过某物从更改 的值时Sheet2,它可以工作,但是例如,如果我将其定义为=Sheet1!A7, 和 change Sheet1's A7,则什么也不会发生。

我怎样才能让它工作?

4

1 回答 1

1

Well, the linked thread deals with the problem that you want to find out the cell that is recalculated by the current change. (Anyway, the Dependents method only works for formula on the active sheet so this would not work across sheets). In your case, you already know that you only want to monitor one specific (formula) cell.
So, I'd simply go with this:
Put this code in sheet 1 if you know that Sheet2!A1 only depends on values on sheet1.
Just catch all changes and look at your cell each time:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Worksheets("Table2").Range("A1").Value >= 1000 Then
        MsgBox "Something requires attention"
    End If
End Sub

Make sure that you use Worksheets(...).Range - a blank Range can be the source of sleepless nights of error-hunting, it refers to the worksheet where the code is located if the code is in a worksheet module and to the active sheet if it is in another code module.

于 2013-06-27T20:19:14.223 回答