如何检测单元格是否通过“ = IF()”公式而不是用户更改

时间:2018-07-24 09:39:39

标签: excel vba excel-vba if-statement cell

我读了很多页面,但是,如果值不是通过“ if function”手动更改的,则没有一个解决方案。

我得到的代码是:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Intersect(Target, Me.Range("A18:A30")) Is Nothing Then Exit Sub
    Application.EnableEvents = False 'to prevent endless loop
    On Error GoTo Finalize 'to re-enable the events
    MsgBox "You changed THE CELL!"
Finalize:
    Application.EnableEvents = True
End Sub

仅在我手动更改值的情况下有效。

谢谢。

3 个答案:

答案 0 :(得分:3)

Another solution; instead of triggering your function every time when your worksheet recalculates, add a function in a module:

Function DetectChange() As Integer
    MsgBox "You changed THE CELL!"
    DetectChange = 0
End Function

Assuming the outcome of your formula is numeric:(otherwise outcome of function must be a empty string and the "+" must be "&") Add to your IF-formula at the end ...+Detectchange() Now there will be a msgbox only when your formula is recalculated

Edit by Darren Bartrup-Cook:

I found this code gave worked when the formula recalculated. It didn't fire if I changed a cell that doesn't affect the cell it's entered to and it didn't fire using Calculate Now or Calculate Sheet.
It did occasionally fire for all formula that I used the function in, but that seemed to be when I was debugging - maybe further investigation needed.

Public Function DetectChange()
    MsgBox "You changed cell " & Application.Caller.Address
End Function  

e.g.:
=IF(A1=1,A2,A3) & DetectChange() entered in cell A4 displays the message "You changed cell $A$4" if cells A1, A2 or A3 is changed.

答案 1 :(得分:1)

Sheet1中编写并运行TestMe子:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Intersect(Target, Me.Range("A1:A30")) Is Nothing Then Exit Sub
    Application.EnableEvents = False
    On Error GoTo Finalize
    MsgBox "You changed THE CELL!"
Finalize:
    Application.EnableEvents = True
End Sub

Sub TestMe()
    Range("A1") = 34
End Sub

在我的PC上运行正常。


如果通过内置的Excel函数更改了单元格,则@Vincent G的注释将给出正确的答案:

当用户或外部链接更改工作表上的单元格时,会发生

Worksheet_Change事件 。当重新计算期间单元格发生更改时,不会发生此事件。使用Calculate事件捕获工作表重新计算。


如果您要根据Range(A18:A30)上的某些更改来跟踪计算事件,这是一个可行的解决方案:

  • 将新的工作表添加到您的工作簿(Sheet2);
  • 在当前工作表中编写Calculate事件:

    Private Sub Worksheet_Calculate()        
        Dim cell As Range
        For Each cell In Sheet2.Range("A18:A30")
            If cell <> Sheet1.Range(cell.Address) Then
                cell = Sheet1.Range(cell.Address)
            End If
        Next cell
    End Sub
    
  • Sheet2中编写一个事件,以捕获更改。

答案 2 :(得分:0)

As simple as @Vincent G says.

Private Sub Worksheet_Calculate()

     Call YourFunction

End Sub