Excel VBA to Generate Pie Chart from Dynamic Data - Error 'Object Variable or With Block Variable Not Set'
I just started working with I've searched everywhere and can't find a clear answer. I'm trying to create a pie chart in Excel using VBA that dynamically updates based on the data from a specific range. However, I'm encountering the error message 'Object Variable or With Block Variable Not Set' when I try to set the chart data range. I've already defined the range dynamically, but it seems that the chart object isnโt being recognized correctly. Hereโs what I have so far: ```vba Sub CreateDynamicPieChart() Dim ws As Worksheet Dim chartObj As ChartObject Dim chartRange As Range Dim lastRow As Long Set ws = ThisWorkbook.Sheets("DataSheet") lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row Set chartRange = ws.Range("A1:B" & lastRow) ' Assuming data is in columns A and B ' Check if chart exists and create if it doesn't On Error Resume Next Set chartObj = ws.ChartObjects("DynamicPieChart") On Error GoTo 0 If chartObj Is Nothing Then Set chartObj = ws.ChartObjects.Add(Left:=100, Width:=375, Top:=50, Height:=225) chartObj.Name = "DynamicPieChart" End If With chartObj.Chart .SetSourceData Source:=chartRange .ChartType = xlPie .HasTitle = True .ChartTitle.Text = "Dynamic Data Pie Chart" End With End Sub ``` Iโve verified that the data in columns A and B is correct and the range is properly defined. The error seems to occur during the `SetSourceData` call. I'm using Excel 2016 on Windows 10. Is there something obvious that Iโm missing, or any best practices to ensure that the chart is created correctly every time? Any help would be greatly appreciated! This is part of a larger application I'm building. How would you solve this? This is part of a larger CLI tool I'm building.