Error HRESULT E_FAIL when iterating through for loop only


I'm seeing the good old "System.Runtime.InteropServices.COMException HResult=0x80004005 Message=Error HRESULT E_FAIL has been returned from a call to a COM component" error when attempting to find an item via a for loop as shown below:

For i = 1 to itemList.Count
    oObject = itemList.Item(i)

But not if I hardcode the index, this finds item 1 without issue:

oObject = itemList.Item(1)

Obviously I don't want to do that and need to search through all the objects in my "itemList" to find the one I'm looking for.

I'm being intentionally vague because the software I'm working in is Dassault 3D Experience but am writing macros for it through Visual Studio 2017. I'm not sure where to even start debugging this sort of issue so any suggestions would be appreciated. Thanks.

Edit: adding full code of what I'm trying to do here (find an object, display its name, also select it on screen to double check. I will later add a check to make sure the object found in each loop is really what I'm looking for). All variables have been declared before this section.

selactive = CATIA.ActiveEditor.Selection

product1Service = CATIA.ActiveEditor.GetService("PLMProductService")
oRootOcc = product1Service.RootOccurrence
cVPMOccurrences = oRootOcc.Occurrences

For i = 1 to cVPMOccurrences.Count
      oVPMOccurrence = cVPMOccurrences.Item(i)

The line that fails is oVPMOccurrence = cVPMOccurrences.Item(i)
asked on Stack Overflow Nov 24, 2020 by Andrew Briefman • edited Nov 25, 2020 by Andrew Briefman

2 Answers


Can you do something like this with a For Each loop?

For each oVPMOccurrence as oRootOcc.Occurrence in cVPMOccurrences.Items

Using a For Each means you don't have to worry at all about the index

Not sure what the type of oVPMOccurrence is as you haven't specified

answered on Stack Overflow Nov 25, 2020 by Hursey

Most indexes in .net are zero base. I don't know what itemList is but I suspect the index of the first item is 0.

For i = 0 to itemList.Count - 1
    oObject = itemList.Item(i)

Not sure why you want to overwrite the value of oObject on every iteration.

answered on Stack Overflow Nov 24, 2020 by Mary

User contributions licensed under CC BY-SA 3.0