VBA: How to prevent 'Object variable or With block variable not set' scenarios when iterating through a collection?
I've encountered a strange issue with I'm integrating two systems and I tried several approaches but none seem to work. I'm working with an 'Object variable or With block variable not set' behavior in my VBA code while trying to iterate through a collection of shapes within an Excel worksheet. The goal is to change the fill color of specific shapes based on their names. I've been initializing a shape collection and then looping through it, but I keep running into this behavior and it's not clear where I'm going wrong. Here's the relevant part of my code: ```vba Dim ws As Worksheet Dim shp As Shape Dim shapeNames As Collection Set ws = ThisWorkbook.Sheets("Sheet1") Set shapeNames = New Collection ' Assuming these shapes exist on the sheet shapeNames.Add "Circle" shapeNames.Add "Square" For Each shp In ws.Shapes If Not IsError(Application.Match(shp.Name, shapeNames, 0)) Then shp.Fill.ForeColor.RGB = RGB(255, 0, 0) ' Change color to red End If Next shp ``` When I run the code, it throws the behavior at `For Each shp In ws.Shapes`. I've verified that the shapes exist on the sheet, but I'm not sure why this behavior is happening. I've also tried manually checking if `ws.Shapes` contains any items, and it does. I've seen similar issues related to uninitialized objects, but I believe I've declared everything correctly. Could it be a timing scenario with shape loading? What is the best way to handle this situation? Any help would be appreciated! I'm working on a service that needs to handle this. What's the best practice here? For context: I'm using Vba on Windows. Any ideas what could be causing this? What's the best practice here? I'm working on a CLI tool that needs to handle this.