Get instance Id of assembly component using SOLIDWORKS API

Edit ArticleEdit Article

This example extracts the component instance index from the component's name using SOLIDWORKS API.

Component instance id option in the component properties dialog
Component instance id option in the component properties dialog

Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim swSelMgr As SldWorks.SelectionMgr
Dim swComp As SldWorks.Component2

Sub main()

    Set swApp = Application.SldWorks

    Set swModel = swApp.ActiveDoc
    If Not swModel Is Nothing Then
        Set swSelMgr = swModel.SelectionManager
        Set swComp = swSelMgr.GetSelectedObjectsComponent3(1, -1)
        If Not swComp Is Nothing Then
            Dim instId As Integer
            Dim compName As String
            compName = swComp.Name2
            instId = CInt(Right(compName, Len(compName) - InStrRev(compName, "-")))
            MsgBox "Selected component's instance id is " & instId
            MsgBox "Please select component"
        End If
        MsgBox "Please open assembly"
    End If
End Sub


All articles and code at CodeStack are now open-source and hosted on GitHub. If you want to contribute by modifying existing articles and code snippets, submitting new ones, reporting errors and bugs etc. please follow this blog post for more information. We appreciate any contribution.

Product of Xarial Product of Xarial