By Barbara Han
To replace a component via the Inventor API, you can use the ComponentOccurrence.Replace method. This method takes two parameters:
1. The full file name of the file to be used to replace the existing occurrence.
2. A Boolean value that indicates whether the current occurrence should be replaced or all the instances of this occurrence.
When replacing occurrences, the behavior is the same as that of the Replace command from the Inventor UI. If the new file that you are replacing with is the same as the original one in geometry, the constraints will be maintained. If the geometry is different Inventor will not know how to keep the constraints and they will not be maintained. The following are the code sample from VB.NET and C#:
VB.NET
Private Sub ReplaceOccurrence()
If m_inventorApplication.ActiveDocument.DocumentType <> DocumentTypeEnum.kAssemblyDocumentObject Then
MsgBox("An assembly file must be open")
Exit Sub
End If
‘get the active assembly document
Dim oAssemDoc As AssemblyDocument = m_inventorApplication.ActiveDocument
‘get the assembly component definition
Dim oAssemDef As AssemblyComponentDefinition = oAssemDoc.ComponentDefinition
‘get the assembly occurrences
Dim oCompOccs As ComponentOccurrences = oAssemDef.Occurrences
If oCompOccs.Count = 0 Then
MsgBox("Assembly does not contain any occurrence")
Exit Sub
End If
‘get the first occurrence
Dim oCompOcc As ComponentOccurrence = oCompOccs(1)
‘replace the occurrence with another part/assembly (specify full file name)
Call oCompOcc.Replace("C:\case\part1.ipt", False)
End Sub
C#
public void ReplaceOccurrence ()
{
if (m_inventorApplication.ActiveDocument.DocumentType != DocumentTypeEnum.kAssemblyDocumentObject )
{
MessageBox.Show ("An assembly file must be open");
return;
}
//get the active assembly document
AssemblyDocument oAssemDoc = (AssemblyDocument)m_inventorApplication.ActiveDocument;
//get the assembly component definition
AssemblyComponentDefinition oAssemDef = oAssemDoc.ComponentDefinition;
//get the assembly occurrences
ComponentOccurrences oCompOccs = oAssemDef.Occurrences;
if (oCompOccs.Count == 0)
{
MessageBox.Show("Assembly does not contain any occurrence");
return;
}
//get the first occurrence
ComponentOccurrence oCompOcc = oCompOccs[1];
//replace the occurrence with another part/assembly (specify full file name)
oCompOcc.Replace("C:\\case\\part1.ipt", false);
}
Note: In the case of the second parameter of Replace method being True (all instances of this occurrence are to be replaced), you can use the ReplaceReference method via apprentice API or Inventor API. This blog article illustrating this.

Leave a Reply