Add Smart Components Example (VBA)
This example shows how to add Smart Components to an assembly.
'----------------------------------------------------------------------------
' Preconditions:
' Open:
' <SolidWorks_install_dir>\samples\tutorial\smartcomponents\stepped_shaft.sldasm
'
' Postconditions:
' 1.
<SolidWorks_install_dir>\samples\tutorial\smartcomponents\Bearing.sldprt
' is
opened.
' 2.
<SolidWorks_install_dir>\samples\tutorial\smartcomponents\Bearing.sldprt
' is
added as three separate Smart Components at the
' specified
coordinates to stepped_shaft.sldasm.
'
' NOTE: Because
this assembly is used in a SolidWorks
' online
tutorial, when you close the assembly document, do
' not
save any changes.
'---------------------------------------------------------------------
Option Explicit
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim swAssy As SldWorks.AssemblyDoc
Dim tmpPath As String
Dim tmpObj As SldWorks.ModelDoc2
Dim boolstat As Boolean
Dim swcomponent As SldWorks.Component2
Dim AssemblyTitle As String
Dim errors As Long
Dim warnings As Long
Sub Main()
Set
swApp = Application.SldWorks
Set
swModel = swApp.ActiveDoc
'
Get title of assembly document
AssemblyTitle
= swModel.GetTitle
boolstat
= True
Dim
strCompModelname As String
strCompModelname
= "Bearing.sldprt"
'
Because the component resides in the same folder as the assembly, get
'
the assembly's path and use it when opening the component
tmpPath
= Left(swModel.GetPathName, InStrRev(swModel.GetPathName, "\"))
'
Open the component
Set
tmpObj = swApp.OpenDoc6(tmpPath
+ strCompModelname, swDocPART, 0, "", errors, warnings)
'
Check to see if the file is read-only or cannot be found; display error
'
messages if either
If
warnings = swFileLoadWarning_ReadOnly Then
MsgBox
"This file is read-only."
boolstat
= False
End
If
If
tmpObj Is Nothing Then
MsgBox
"Cannot locate the file."
boolstat
= False
End
If
'Re-activate
the assembly so that you can add the component to it
Set
swModel = swApp.ActivateDoc2(AssemblyTitle,
True, errors)
Set
swAssy = swModel
'
Add the component to the assembly document
'
Print the component name to the Immediate Window
Set
swcomponent = swAssy.AddSmartComponent(strCompModelname,
0, 0.13, -0.1)
Debug.Print
swcomponent.Name2
Set
swcomponent = swAssy.AddSmartComponent(strCompModelname,
0, 0.13, -0.42)
Debug.Print
swcomponent.Name2
Set
swcomponent = swAssy.AddSmartComponent(strCompModelname,
0, 0.13, 0.49)
Debug.Print
swcomponent.Name2
swModel.ClearSelection2 (True)
End Sub