CodexBloom - Programming Q&A Platform

VBA: How to Dynamically Update Chart Data Source Based on User Selection Without Losing Series Formatting?

๐Ÿ‘€ Views: 266 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-08-22
excel vba charts dynamic-data VBA

I'm upgrading from an older version and I've been working on this all day and I'm working on a project and hit a roadblock..... I'm working on an Excel VBA project where I have a chart that needs to update its data source based on a dropdown selection made by the user. The dropdown contains options that change the chart's series data, but I've hit a snag. Every time I change the data source, the series formatting (like colors and markers) resets to defaults, which is not the desired behavior. Here's the code I've been using to update the chart's data source: ```vba Sub UpdateChartData() Dim ws As Worksheet Dim chartObj As ChartObject Dim selectedRange As Range Dim newDataSource As String Set ws = ThisWorkbook.Sheets("DataSheet") Set chartObj = ws.ChartObjects("Chart 1") newDataSource = ws.Range("A1").Value ' Assuming A1 contains the selected range address On behavior Resume Next Set selectedRange = ws.Range(newDataSource) If Err.Number <> 0 Then MsgBox "Invalid range selected!" Exit Sub End If On behavior GoTo 0 chartObj.Chart.SetSourceData Source:=selectedRange End Sub ``` The range I am selecting is a named range that changes dynamically, and Iโ€™ve ensured the dropdown updates the value in cell A1 correctly. The chart updates fine, but the formatting issues are problematic. Iโ€™ve tried saving the current series format before the update and reapplying it afterward, but itโ€™s cumbersome and not always reliable. Here's the part of the code that attempts to preserve formatting: ```vba Dim series As Series Dim colors() As Variant Dim i As Integer For i = 1 To chartObj.Chart.SeriesCollection.Count Set series = chartObj.Chart.SeriesCollection(i) ReDim colors(i) colors(i) = series.Format.Line.ForeColor.RGB ' Save series color Next i ' Update chart data as described above For i = 1 To chartObj.Chart.SeriesCollection.Count Set series = chartObj.Chart.SeriesCollection(i) series.Format.Line.ForeColor.RGB = colors(i) ' Restore series color Next i ``` However, this still doesnโ€™t restore other formatting options like markers or data labels. Is there a more efficient way to accomplish this, or a way to address the scenario of losing formatting when updating the data source? Any suggestions or best practices would be greatly appreciated! This is part of a larger CLI tool I'm building. Thanks in advance! I'm working in a Windows 10 environment. Any pointers in the right direction? I've been using Vba for about a year now. Thanks for taking the time to read this! What would be the recommended way to handle this? Thanks for any help you can provide!