CodexBloom - Programming Q&A Platform

Excel Macro to Update Chart Data Source Based on Cell Value Change optimization guide

👀 Views: 0 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-13
excel vba chart automation

I'm reviewing some code and I'm testing a new approach and I am trying to create a VBA macro that updates the data source of a chart whenever a specific cell value changes. I have a chart that displays data from a range `A1:B10`, and I want it to update to `A1:B20` when the value in cell `C1` is changed to 'Expand'. However, nothing happens when I change the value in `C1`. I have implemented the following code in the `ThisWorkbook` module: ```vba Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range) If Not Intersect(Target, Sh.Range("C1")) Is Nothing Then If Target.Value = "Expand" Then Dim cht As ChartObject Set cht = Sh.ChartObjects("Chart 1") ' replace with your chart name cht.Chart.SetSourceData Source:=Sh.Range("A1:B20") Else Dim cht As ChartObject Set cht = Sh.ChartObjects("Chart 1") cht.Chart.SetSourceData Source:=Sh.Range("A1:B10") End If End If End Sub ``` I've checked that the chart name is correct, and the ranges are valid. However, when I change the value in `C1`, it doesn't trigger the `Workbook_SheetChange` event. I also ensured that macros are enabled, and I did try adding a message box within the event to confirm if it's firing, but it never shows up. I'm using Excel 2016 on Windows 10, and I've tried debugging by placing breakpoints but the control never seems to enter the `Workbook_SheetChange` subroutine. Is there something I'm missing or any potential conflicts with other event handlers? Any insights would be greatly appreciated! Thanks in advance! Cheers for any assistance! Any ideas what could be causing this? I recently upgraded to Vba 3.9. What's the best practice here?