简体   繁体   中英

Excel/VBA update cell every time value in another cell changes

I'm very new to VBA. I have a cell in the worksheet that live updates a value. the Value changes about once every month. Is there a way for me to record the day that the value changed in an adjacent cell? For example, If the value in A1 changes from 5 to 6 today, I just want to record today's date in A2.

I don't really need to keep a record of previous changes.

Thank you so much!

If you are using a Bloomberg function in cell A1 like BDP() or BDH() or BDS() , then you could use the Worksheet_Calculate() event macro to detect changes in that cell.

In this example, I use cell A3 as a "memory" to avoid re-posting the date too often:

Private Sub Worksheet_Calculate()
    Application.EnableEvents = False
        If [A1] <> [A3] Then
            [A3] = Range("A1").Value
            [A2] = Date
            MsgBox "Date recorded"
        End If
    Application.EnableEvents = True
End Sub

The Worksheet_Change() is being fired when something on the sheet changes its value, so add something like this to your Sheet-Codemodule:

Private Sub Worksheet_Change(ByVal Target As Range)

If Target.Address = "$A$1" Then

    Debug.Print "A1 has been changed!"
    'do something
End If
End Sub

Update:

It seems you need the calculate event also as you're using a formula. you could try something like this:

Private Sub Worksheet_Calculate()

    Application.EnableEvents = False

    ActiveSheet.Calculate
    DoEvents

    With Range("A1")
        .Value = .Value
        DoEvents
    End With

    Application.EnableEvents = True

End Sub

Private Sub Worksheet_Change(ByVal Target As Range)

    If Target.Address = "$A$1" Then
        Range("A2").Value = Date
    End If

End Sub

You could use the Worksheet_SelectionChange event. I guess it depends on what else you're doing in the worksheet as to whether it would fire or not. You'd have to compare the value in A1 against what was in A1 previously which would be stored in another cell.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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