Replace Component Example (VBA)
This example shows how to replace a component with a different component.
'-------------------------------------------------------------
' Preconditions:
' 1. Open an assembly.
' 2. Select component.
' 3. Verify that install_dir\samples\tutorial\api\block.sldprt
' exists.
'
' Postconditions:
' 1. Replaces the selected component with the component in the
' specified file.
' 2. Examine the Immediate window, FeatureManager design tree,
' and assembly.
'-------------------------------------------------------------
Option Explicit
Sub main()
Const sFileName As String = "C:\Program Files\SolidWorks Corp\SolidWorks\samples\tutorial\api\block.sldprt"
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim swAssy As SldWorks.AssemblyDoc
Dim swSelMgr As SldWorks.SelectionMgr
Dim swSelComp As SldWorks.Component2
Dim bRet As Boolean
Set swApp = CreateObject("SldWorks.Application")
Set swModel = swApp.ActiveDoc
Set swAssy = swModel
Set swSelMgr = swModel.SelectionManager
Set swSelComp = swSelMgr.GetSelectedObjectsComponent4(1, -1)
bRet = swAssy.ReplaceComponents(sFileName, "", True, True)
Debug.Print "File = " & swModel.GetPathName
Debug.Print " Selected component to replace = " & swSelComp.Name2
Debug.Print " Selected replacement component path = " & swSelComp.GetPathName
Debug.Print " Component replaced? " & bRet
End Sub