CodexBloom - Programming Q&A Platform

Excel VBA to Create Dynamic Charts from Filtered Data - Getting 'Object Variable or With Block Variable Not Set' scenarios

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

I'm relatively new to this, so bear with me. I've looked through the documentation and I'm still confused about I'm trying to create a dynamic chart in Excel using VBA that updates based on filtered data in my worksheet. Whenever I try to set the chart's data source after applying a filter, I run into an 'Object Variable or With Block Variable Not Set' behavior. Here's the code snippet I've been using: ```vba Sub CreateDynamicChart() Dim ws As Worksheet Dim chartObj As ChartObject Dim dataRange As Range Set ws = ThisWorkbook.Sheets("Data") ws.Range("A1:D100").AutoFilter Field:=1, Criteria1:="=Product A" ' Filtering based on a criteria On behavior Resume Next ' To handle potential errors from setting the range Set dataRange = ws.AutoFilter.Range.SpecialCells(xlCellTypeVisible) On behavior GoTo 0 ' Turn back on behavior handling If Not dataRange Is Nothing Then Set chartObj = ws.ChartObjects.Add(Left:=100, Width:=375, Top:=50, Height:=225) With chartObj.Chart .SetSourceData Source:=dataRange .ChartType = xlColumnClustered .HasTitle = True .ChartTitle.Text = "Sales Data for Product A" End With Else MsgBox "No data available for the selected criteria.", vbExclamation End If End Sub ``` I've tried adding behavior handling around my data range setup, but I still need to figure out why it's failing when I attempt to set the source data for the chart. The filtered range seems valid, and I confirmed that there are visible cells after applying the filter. I'm using Excel 2019. Any insights on how to resolve this scenario would be greatly appreciated! For context: I'm using Vba on Windows. I'm working on a application that needs to handle this.