How to Use Excel VBA to Run a Macro When the Cell Value Changes – 3 Examples

 

Overview:

Overview of running Vba macro when cell value changes

 


Example 1. Running a Macro When a Specific Cell Value Changes

The dataset showcases students and their marks. A dynamic table was created to find the top n number of students (see How to Create a Dynamic Top 10 List in Excel).

To display a message in E18 when the value in F4 changes, create an Event and enter a code in the Worksheet_Change event.

Dataset to run macro when a specific cell value changes

 

  • Right-click your worksheet name and select View Code.

Access code module

  • In the code window, select the Worksheet in the left drop-down menu, and Change in the right drop-down menu. This will create a subroutine.

Create Change event for the worksheet

  • Enter the following code.
Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address = "$F$4" Then
        Range("E18").Value = "These " & Target.Value & " students will get a scholarship"   
    End If
End Sub

VBA Code to run Macro when a specific cell value changes

Code Breakdown

If Target.Address = "$F$4" Then
        Range("E18").Value = "These " & Target.Value & " students will get a scholarship"
End If

The Target parameter inside the event handler subroutine represents the changed cell. If the condition is TRUE ( F4 changed), the code displays a message in E18. This code updates the message whenever F4 changes.

Read More: How to Save Macros in Excel Permanently


Example 2 – Running a Macro When a Cell Value in a Range is Changed

 

Dataset run macro when a cell value in a range is changed

  • Right-click  your worksheet name and select View Code.

Access code module to create event

  • Create a Worksheet_Change subroutine following the previous method. Enter this code.
Private Sub Worksheet_Change(ByVal Target As Range)
           If Not Intersect(Target, Range("C5:C20")) Is Nothing Then
                     MsgBox Range("B" & Target.Row).Value & "'s mark has been changed"
           End If
End Sub

VBA code to run macro when a cell value in a range is changed

Code Breakdown

If Not Intersect(Target, Range("C5:C20")) Is Nothing Then
  • The Intersect function checks if the Target range (the range that was changed) intersects with C5:C20 in the worksheet.
MsgBox Range("B" & Target.Row).Value & "'s mark has been changed"
  • This part of the code retrieves the value of the cell in column B corresponding to the row of the changed cell. It creates a message that is concatenated with the retrieved value.

Read More: How to Edit Macros in Excel


Example 3 – Running a Macro When the Value in the Drop-Down List Changes

A drop-down list was created in F4.

  • Select F4.
  • In Data, go to Data Tools and select Data Validation in the Data Validation drop-down.

Access Data Validation from Data ribbon

  • In Allow, choose List.
  • In Source, enter numbers with commas (,) in between.
  • Click OK.

Create data validation list

The drop-down list was added to F4.

Drop-down list

  • Right-click your worksheet name and select View Code.
  • Create a Worksheet_Change subroutine following the previous method. Enter this code.
Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address = "$F$4" Then
        Range("E18").Value = "These " & Target.Value & " students will get scholarship"
    End If
End Sub

VBA Code to run Macro when a specific cell value changes

If you change the value in F4 using the drop-down list, a dynamic message will be displayed in E18.


How to Run a VBA Macro When the Cell Value Changes using a Formula In Excel

The dataset below contains a formula in column F based on the SUM function to calculate the total mark for each student.

You want to create a VBA macro, so that a message can be displayed if formulas change.

Enter the code in the Worksheet_Calculate event.

Dataset to run vba macro when cell value changes by formula

  • Right-click your worksheet name and select View Code.
  • Select Worksheet in the left drop-down menu, and Calculate in the right drop-down menu. This will create a subroutine.

Create Calculate event for the worksheet

  • Enter the following code.
Private Sub Worksheet_Calculate()
Static oldval(6 To 10) As Variant
Dim flag As Boolean
flag = False
    For i = 6 To 10
        If Range("F" & i).Value <> oldval(i) Then
            oldval(i) = Range("F" & i).Value
            Dim studentName As String
            studentName = Range("B" & i).Value
            MsgBox studentName & "'s mark is updated"
            flag = True
        Exit For
        End If
    Next i
    
    If flag = False Then
        For i = 6 To 10
            oldval(i) = Range("F" & i).Value
        Next i
    End If
End Sub

VBA code to run vba macro when cell value changes by formula

Code Breakdown

Static oldval(6 To 10) As Variant

declares a static array named oldval to store the previous values of the cells in column F (row 6 to 10). The Static keyword means that the array will retain its values between subsequent calls to the event handler, ensuring you can track changes over time.

Dim flag As Boolean
flag = False

a Boolean variable flag is declared. The value is set to False.

For i = 6 To 10
        If Range("F" & i).Value <> oldval(i) Then
            oldval(i) = Range("F" & i).Value
            Dim studentName As String
            studentName = Range("B" & i).Value
            MsgBox studentName & "'s mark is updated" 
            flag = True
            Exit For
        End If
Next i

loops through rows 6 to 10, examining whether the current formula in cell F(i) yields a distinct result from the previously stored value in the oldval array. Upon detecting any alteration, it updates the oldval array with the present value. The corresponding student’s name is found in column B and a message box is displayed with the name of the student whose marks have been updated. The flag variable serves as a tracker to signal the presence of a change. As soon as it detects the first updated mark, the loop presents a singular message box.

If flag = False Then
        For i = 6 To 10
            oldval(i) = Range("F" & i).Value
        Next i
End If

evaluates If flag = False then and checks if there is any change during the iteration. If the flag is still False, it means there was no change detected in the formula results within F6:F10. The code updates the oldval array with the current values of  F6:F10, storing the latest formula results.

If you change the value of the SUM formula, the code will activate the message, stating the student’s name.


How to Run a VBA Macro When the Cell is Selected

You want to display the content or value of a selected in the Status Bar.

Create an Event to trigger it every time you select a cell. The code must be in the Worksheet_SelectionChange event.

  • Right-click your worksheet name and select View Code.
  • Select Worksheet in the left drop-down menu, and it will automatically select the SelectionChange event and create a subroutine.

Create SelectionChange Event for the worksheet

  • Enter this code to display the selected cell content.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Not Intersect(Target, Range("C6:F10")) Is Nothing Then
        Application.StatusBar = Range("B" & Target.Row).Value & " got " & Target.Value & " in " & Range(Cells(5, Target.Column).Address).Value
    End If
End Sub

VBA code to run vba macro when cell is selected

Code Breakdown

If Not Intersect(Target, Range("C6:F10")) Is Nothing Then

The Intersect function checks whether the selected cell (Target) intersects with the range C6:F10.

Application.StatusBar = Range("B" & Target.Row).Value & " got " & Target.Value & " in " & Range(Cells(5, Target.Column).Address).Value

sets the message in the  Status Bar. It collects the value from selected cell and retrieves the Student’s name and subject and concatenates the message.

  • If you select any cell, you will see its content in the Status Bar.

Frequently Asked Questions

1. Are there alternative methods or Excel features that I can use instead of VBA to respond to cell value changes?
Ans: Yes. You can use Excel’s built-in features like Data Validation, Conditional Formatting, or formulas with Worksheet Functions to trigger actions based on cell changes.

2. Can I use VBA to trigger actions in other worksheets or workbooks based on cell value changes in a specific worksheet?
Ans: Yes.You can use a code to trigger actions in other worksheets or workbooks based on changes. VBA allows for automation and coordination between different sheets or workbooks.

3. Are there any limitations or considerations to keep in mind when using VBA to respond to cell value changes?
Ans: Yes. Consider the following:

  • Performance impact: Frequent changes can slow down Excel.
  • Error handling: Handle potential errors to avoid crashes.
  • Event triggers: Avoid recursive events by disabling them during execution.
  • Compatibility: Ensure compatibility with different Excel versions.
  • Security: Enable macros only from trusted sources to prevent potential security risks.

Download Practice Workbook

Download this file to practice.


Related Articles

Get FREE Advanced Excel Exercises with Solutions!
Mehedi Hassan
Mehedi Hassan

Mehedi Hassan, having earned a BSc in Naval Architecture & Engineering from Bangladesh University of Engineering and Technology, functions as an Excel & VBA Content Developer at ExcelDemy. His deep interest in research and innovation aligns seamlessly with his fervor for Excel. In this role, Mehedi not only skillfully addresses challenging issues but also exhibits enthusiasm and expertise in gracefully navigating intricate situations, emphasizing his unwavering dedication to consistently delivering outstanding content. His interests are Advanced... Read Full Bio

2 Comments
  1. Hello,

    Thanks for the post, contains useful information.

    I suggest that you make explicitly clear that the macro runs every time *any* cell in the concerned sheet changes.

    I have been faced with a performance problem when I needed to associate an action with a change in value in just ONE specific cell ($K$10) in my Book1 Sheet1.

    Book1 Sheet1 has hundreds of cells with values that need to be updated from time to time :
    – any of these updates, having nothing to do with cell $K$10, triggers the execution of the macro
    – many cells in have formulas that reference other cells (Excel calls them ‘dependents’) f.i. cell $V$7 has formula ‘= $A$1 + $A$2’. The macro is called when cell $A$1 (or $A$2) is updated and then again when the dependent cell $V$7 is updated
    – finally many cells in Sheet1 have links to external workbooks. Every time I open Book1 and choose to update links the macro runs for every update that is made

    Granted, the macro runs ‘for nothing’, i.e. the ‘If Intersect’ evaluates to ‘false’ since my only cell of interest, $K$10, is not impacted, but still has a very heavy impact on performance.

    Thanks again for the post, I learned a lot by reading through it.

    Regards,

    nunof

    • Reply Lutfor Rahman Shimanto
      Lutfor Rahman Shimanto Dec 27, 2023 at 6:57 PM

      Hello NUNOF

      Thanks for your beautiful words. Your appreciation means a lot to us. We are delighted to know you have learned a lot from our blog.

      The issue you describe hampers performance for sure in such scenarios. I have gone through the article and also investigated your problem. What I have found: Perhaps you are calling your desired macro within another worksheet event like Worksheet_Calculate instead of the Worksheet_Change event of cell $K$10, which results in calling the macro unintentionally.

      When the cell values change by formulas, the Worksheet_Change event will not trigger. So, call your macro or sub-procedure within a change event. In your case, the code within the sheet module can be like the following:

      
      Private Sub Worksheet_Change(ByVal Target As Range)
      
          If Not Intersect(Target, Range("K10")) Is Nothing Then
              
              Call GreetingToNUNOF
          
          End If
      
      End Sub
      
      
      Sub GreetingToNUNOF()
          MsgBox "Hello from ExcelDemy!"
      End Sub
      

      Hopefully, you have found the idea to overcome your situation. Good luck!

      Regards
      Lutfor Rahman Shimanto
      Excel & VBA Developer
      ExcelDemy

Leave a reply

Advanced Excel Exercises with Solutions PDF

 

 

ExcelDemy
Logo