€0.00
0

SOLIDWORKS Assembly API: Components, Traversal and Mates

A practical guide to the SOLIDWORKS assembly API: IAssemblyDoc, components, traversal, lightweight states, adding components, mates and speed tips.
SOLIDWORKS Assembly API: Components, Traversal and Mates
Picture of Amen Jlili

Amen Jlili

Amen Jlili is the founder and technical director of Blue Byte Systems Inc., a software company in Vancouver, Canada, specializing in automating SOLIDWORKS and PDM.

The SOLIDWORKS assembly API centers on two interfaces: IAssemblyDoc, which represents the open assembly document, and IComponent2, which represents each instance of a part or subassembly inside it. You get the components with IAssemblyDoc.GetComponents (or by walking down from the root component), read their file path, configuration, suppression state and position from IComponent2, and call GetModelDoc2 when you need the underlying part or assembly model. This guide covers how to work with SOLIDWORKS API assembly components in practice: traversal, lightweight vs resolved states, configurations, adding components, mates, and the performance switches that keep large assembly macros fast.

The SOLIDWORKS assembly API object model

Every open document is an IModelDoc2. When that document is an assembly, the same object can be cast to IAssemblyDoc to reach assembly specific members. In VBA that cast is just an assignment:

Dim swModel As SldWorks.ModelDoc2
Dim swAssy As SldWorks.AssemblyDoc
Set swModel = swApp.ActiveDoc
If swModel.GetType = swDocASSEMBLY Then Set swAssy = swModel

The key objects and how they relate:

Interface Represents Common members
IModelDoc2 Any open document GetPathName, GetType, Extension, ConfigurationManager
IAssemblyDoc Assembly specific API GetComponents, GetComponentCount, AddComponent5, AddMate5, ResolveAllLightWeightComponents
IConfiguration A configuration of the assembly GetRootComponent3, Name
IComponent2 One instance in the assembly Name2, GetPathName, ReferencedConfiguration, GetModelDoc2, GetChildren, Transform2

An important point that trips up many first macros: a component is an instance, not a file. A bolt used 40 times is 40 IComponent2 objects that all point to the same .sldprt and usually the same IModelDoc2. If your goal is to process each file once (export, property update), collect unique paths first and process the files afterward.

Getting SOLIDWORKS API assembly components

GetComponents

IAssemblyDoc.GetComponents(ToplevelOnly) returns an array of Component2 objects in the active configuration.

  • GetComponents(True) returns only the top level components.
  • GetComponents(False) returns every component at every level, flattened.

Choosing between this and a recursive walk is a recurring question; see Which component traverse method should I use on CADOverflow.

The flat list is convenient for counting or quick checks, but it loses the parent and child structure. When you need indentation, quantities per level, or the parent of a component, use traversal instead.

Recursive traversal from the root component

Every configuration has a root component that represents the assembly itself. Get it with IConfiguration.GetRootComponent3(True) and walk down with IComponent2.GetChildren. We cover this pattern in detail in traversing the assembly tree recursively; here is a compact version that prints the tree with the most useful component data.

Option Explicit

Sub main()
    Dim swApp As SldWorks.SldWorks
    Dim swModel As SldWorks.ModelDoc2
    Dim swConf As SldWorks.Configuration
    Dim swRoot As SldWorks.Component2

    Set swApp = Application.SldWorks
    Set swModel = swApp.ActiveDoc
    If swModel Is Nothing Then Exit Sub
    If swModel.GetType <> swDocASSEMBLY Then Exit Sub

    Set swConf = swModel.GetActiveConfiguration
    Set swRoot = swConf.GetRootComponent3(True)
    TraverseComponent swRoot, 0
End Sub

Sub TraverseComponent(swComp As SldWorks.Component2, level As Integer)
    Dim vChildren As Variant
    Dim i As Long
    Dim swChild As SldWorks.Component2

    vChildren = swComp.GetChildren
    If IsEmpty(vChildren) Then Exit Sub

    For i = 0 To UBound(vChildren)
        Set swChild = vChildren(i)
        Debug.Print String(level * 2, " ") & swChild.Name2 & _
            " | " & swChild.ReferencedConfiguration & _
            " | suppressed=" & swChild.IsSuppressed & _
            " | " & swChild.GetPathName
        TraverseComponent swChild, level + 1
    Next i
End Sub

Name2 returns the instance name (for nested components it includes the parent path), GetPathName returns the full file path, ReferencedConfiguration returns the configuration of the referenced model used by this instance, and IsSuppressed tells you whether to skip it.

Lightweight vs resolved components

SOLIDWORKS can load components lightweight, meaning only a subset of the model data is in memory. That is good for users opening big assemblies and a frequent source of Nothing for macros.

IComponent2.GetSuppression2 returns a swComponentSuppressionState_e value that distinguishes suppressed, lightweight, fully lightweight, resolved and fully resolved states. Practical consequences:

  • GetModelDoc2 can return Nothing for suppressed components and may not give you a usable model for lightweight ones. Always check for Nothing before using the result.
  • Reading file paths, names and transforms works on lightweight components. Many reporting macros never need to resolve anything.
  • Reading custom properties, features or geometry needs the model loaded. Either resolve the component with SetSuppression2(swComponentFullyResolved) or resolve everything at once with IAssemblyDoc.ResolveAllLightWeightComponents.

Resolving a large assembly is expensive. Resolve only when the task requires it. For reading properties from many files, opening each unique file on its own (or using the Document Manager API, which does not need SOLIDWORKS at all) is often faster than resolving the entire assembly.

Configurations and components

GetComponents and the root component both work against a configuration. GetComponents uses the active configuration; GetRootComponent3 works on the configuration object you call it on. Suppression state, referenced configuration and even which components exist can differ per configuration.

Two patterns we use often:

  1. Report on every configuration. Loop over IModelDoc2.GetConfigurationNames, activate each with ShowConfiguration2, and traverse. Activating a configuration triggers a rebuild, so on large assemblies this takes time.
  2. Change which configuration a component uses. Set IComponent2.ReferencedConfiguration to the new configuration name, then rebuild with IModelDoc2.EditRebuild3.

Position: Transform2

IComponent2.Transform2 returns an IMathTransform that describes the component’s position and orientation relative to the assembly origin. Use it with IMathUtility to convert points from component space to assembly space, or call ArrayData on the transform to read the rotation matrix and translation directly. Transform data is the basis for tasks such as computing bounding boxes of assembly components in assembly coordinates.

Keep in mind that API lengths are always in meters, regardless of the document units.

Adding components with AddComponent5

IAssemblyDoc.AddComponent5 inserts a part or subassembly at a given X, Y, Z location (in meters) and returns the new Component2. Its arguments are the file path, a configuration option, a new configuration name, a flag about using the configuration for part references, an existing configuration name, and the coordinates.

The detail that causes most failures: the file being added must already be loaded in memory. Open it first with OpenDoc6 (silently, and it can stay invisible), then call AddComponent5, then close the source document if you do not need it.

Dim errs As Long, warns As Long
Dim swPart As SldWorks.ModelDoc2
Dim swComp As SldWorks.Component2

Set swPart = swApp.OpenDoc6("C:\Parts\bracket.sldprt", swDocPART, _
    swOpenDocOptions_Silent, "", errs, warns)
Set swComp = swAssy.AddComponent5("C:\Parts\bracket.sldprt", _
    swAddComponentConfigOptions_CurrentSelectedConfig, "", False, "", 0, 0, 0)
If swComp Is Nothing Then Debug.Print "AddComponent5 failed"

After adding a component, the assembly may need to be activated again (ActivateDoc3) if opening the part made the part the active document. Added components are not fixed and have no mates, so the next step is usually mating.

Mates overview

Mates are created through the selection manager: select the two entities with the right marks, then call the mate method. IAssemblyDoc.AddMate5 takes the mate type (swMateType_e, such as coincident, parallel, distance or angle), the alignment (swMateAlign_e), a flip flag, the distance and its upper and lower limits, a gear ratio numerator and denominator, the angle and its limits, a positioning-only flag, a lock rotation flag and a width mate option. It returns the created Mate2 feature, with an error code (swAddMateError_e) in the final output argument. Pass zeros for values that do not apply to your mate type.

The general flow:

  1. Clear the selection with IModelDoc2.ClearSelection2.
  2. Select the first entity (a face, plane or axis) with SelectByID2 or by selecting an IEntity with Select4.
  3. Select the second entity, appending to the selection.
  4. Call AddMate5 and check the error status.
  5. Rebuild.

Newer releases also provide a mate feature data approach (CreateMateData and CreateMate on IAssemblyDoc), which separates the definition from the creation and is easier to work with when you build many mates. For a working example of the selection based flow, see our add parallel mate macro.

Selecting the right faces is the hard part in practice. Reference planes and named entities are far more reliable targets than picking faces by coordinates, which break as soon as the geometry changes.

Performance tips for large assembly macros

Assembly macros slow down for three reasons: SOLIDWORKS redraws the graphics area, the FeatureManager tree updates after each change, and the macro does more resolving and rebuilding than necessary. We collected the most effective switches in the most useful API calls to optimize SOLIDWORKS performance; the essentials for assemblies are:

  • ISldWorks.CommandInProgress = True at the start and False at the end. It tells SOLIDWORKS a command is running, which reduces the overhead of out of process calls (especially from standalone EXEs and C# applications).
  • IModelView.EnableGraphicsUpdate = False on the active view while you make many changes, then set it back to True.
  • IFeatureManager.EnableFeatureTree = False to stop the tree from refreshing after each operation.
  • Avoid unnecessary resolving. Read paths and names from lightweight components; resolve only when you need model data.
  • Process unique files once. Build a dictionary keyed by GetPathName during traversal and do the heavy work per file, not per instance.
  • Rebuild once. Batch your changes and call EditRebuild3 at the end instead of after each modification.

Always restore these settings in an error handler. A macro that crashes with graphics updates disabled leaves the user with a frozen looking window.

Community discussions

FAQ

What is the difference between GetComponents(True) and GetComponents(False)?

True returns only top level components. False returns all components at all levels in a flat array. Use recursion with GetChildren when you need the hierarchy.

Why does GetModelDoc2 return Nothing?

The component is suppressed, or it is lightweight and the model is not loaded. Check GetSuppression2, then resolve the component or open the file directly.

How do I get the configuration a component uses?

Read IComponent2.ReferencedConfiguration. Setting the same property changes it, followed by a rebuild.

Do API coordinates use the document units?

No. The SOLIDWORKS API works in meters and radians. Convert to and from document units yourself.

Need help with this?

We write SOLIDWORKS and SOLIDWORKS PDM automation for engineering teams every day, from assembly reporting macros to full add-ins. If you have an assembly task to automate, contact us, or browse the macro library for ready examples.

Need to copy or rename whole assemblies with their references, or publish them to PDF, DXF and STEP, without writing code? PDMPublisher for SOLIDWORKS does it from one CommandManager tab. Start a free 7-day trial.

Need this adapted to your workflow?

We build custom SOLIDWORKS macros, add-ins and PDM automation.

Picture of Amen Jlili

Amen Jlili

Amen Jlili is the founder and technical director of Blue Byte Systems Inc., a software company in Vancouver, Canada, specializing in automating SOLIDWORKS and PDM.

Leave a Comment

0
0
Your Cart
Your cart is emptyReturn to Shop