Home » excel » Run macro when linked cell changes value (Excel VBA)

Run macro when linked cell changes value (Excel VBA)

Posted by: admin April 23, 2020 Leave a comment


I am currently trying to obtain historical information about how the backlog is developing.

My Excel file is based on queries from an Access Database which can give me a view of the current situation.

I would like to automatically run a macro every time the week number changes. I am currently using the following code:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Target.Worksheet.Range("D3")) Is Nothing Then
        Call KPIupdate
    End If
End Sub

The macro that should fire is called KPIupdate

My problem is that the Macro only fires if I click the cell. I would like it to just fire when the number changes. The cell “D3” is linked to another cell with the formula =Weeknum(Today();21)

I hope you can help me

How to&Answers:

According to the MSDN entry for Worksheet_Change:

This event does not occur when cells change during a recalculation. Use the Calculate event to trap a sheet recalculation.

To use Worksheet_Calculate to trap the change in a cell that is set by a formula looking at another cell, you need to set a variable to hold the value of the ‘Target’ and then check if it has changed after the Calculate event fires.

Here is a simple example:

Option Explicit

Private strCurrentWeek As String

Private Sub Worksheet_Calculate()
    If Me.Range("A1").Value <> strCurrentWeek Then
        'the linked cell changed
        Debug.Print "Sheet1!A1 was changed"
        'call another macro
    End If
    'update the new current week
    strCurrentWeek = Me.Range("A1").Value
End Sub

To test this, just set the formula in A1 to be =B1 and then change the value of B1 and check the output in the Immediate window.

You can adapt this code to call KPIupdate where my Debug.Print... statement is.