CodexBloom - Programming Q&A Platform

Excel VBA: How to dynamically adjust chart data range based on filtered rows?

👀 Views: 45 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-01
excel vba charts

I'm having a hard time understanding After trying multiple solutions online, I still can't figure this out... I'm working on an Excel dashboard using VBA, and I'm working with a scenario with updating a chart's data source dynamically after applying filters to a table. The chart is supposed to reflect only the visible rows of the table after a filter is applied, but it seems to be retaining the original data range. I've tried using the `CurrentRegion` property to set the chart data source, but it doesn't seem to capture the changes after filtering. Here's what I have so far: ```vba Sub UpdateChartData() Dim ws As Worksheet Dim chartObj As ChartObject Dim dataRange As Range Set ws = ThisWorkbook.Sheets("Dashboard") Set chartObj = ws.ChartObjects("SalesChart") ' Attempt to set dataRange to visible cells only Set dataRange = ws.Range("A1:B100").SpecialCells(xlCellTypeVisible) chartObj.Chart.SetSourceData Source:=dataRange End Sub ``` However, when I run this code after applying a filter, I get the behavior: "Run-time behavior '1004': Unable to set the SourceData property of the Chart class." I've double-checked that the range covers the relevant data, and the chart name is correct. Is there a specific method or property I should be using to ensure that the chart updates to reflect only the visible rows? Or do I need to modify the approach I'm using for defining the data range? Any suggestions would be greatly appreciated! I'm working on a API that needs to handle this. Any ideas what could be causing this? My team is using Vba for this desktop app. What's the best practice here?