Reorganize Components Example (VBA)
This example shows how to reorder components.
'------------------------------------------
' Preconditions: Assembly document is open.
'
' Postconditions: Selected components are moved to
' target
assembly or sub-assembly.
'------------------------------------------
Macro
Option Explicit
Dim myClass As Class1
Sub main()
Dim
swApp As SldWorks.SldWorks
Dim
myModel As SldWorks.ModelDoc2
Dim
myAssem As SldWorks.AssemblyDoc
Dim
selMgr As SldWorks.SelectionMgr
Dim
selCount As Long, selType As Long
Dim
selObj As Object
Dim
selSource() As SldWorks.Component2
Dim
vSource As Variant
Dim
selTarget As SldWorks.Component2
Dim
boolstatus As Boolean
Set
swApp = Application.SldWorks
Set
myModel = swApp.ActiveDoc
Set
myAssem = myModel
Set
myClass = New Class1
Set
myClass.msrcAssemblyDoc = myAssem
Set
selMgr = myModel.SelectionManager
myModel.ClearSelection2 True
' Interactively select components, all of
which must be from the
' same level of an assembly, to move
Stop
selCount
= selMgr.GetSelectedObjectCount2(0)
If
(selCount = 0) Then
Exit
Sub
End
If
ReDim
selSource(0 To selCount - 1)
Dim
i As Long
For
i = 1 To selCount
selType
= selMgr.GetSelectedObjectType3(i,
0)
If
(selType = SwConst.swSelCOMPONENTS) Then
Set
selObj = selMgr.GetSelectedObject6(i,
0)
Set
selSource(i - 1) = selObj
End
If
Next
i
vSource
= selSource
myModel.ClearSelection2 True
' Interactively select a top-level assembly
or sub-assembly where to move the
' previously selected components
Stop
selCount
= selMgr.GetSelectedObjectCount2(0)
If
(selCount > 0) Then
selType
= selMgr.GetSelectedObjectType3(1,
0)
If
selType = SwConst.swSelCOMPONENTS Then
Set
selObj = selMgr.GetSelectedObject6(1,
0)
If
Not selObj Is Nothing Then
Set
selTarget = selObj
Else
Set
selTarget = myAssem.GetEditTargetComponent
End
If
End
If
End
If
myModel.ClearSelection2
True
' If two components were selected, reorder
the source to follow the target
'where
= SwConst.swReorderComponents_After
'where
= SwConst.swReorderComponents_Before
'Dim
where As Boolean
'where
= SwConst.swReorderComponents_FirstInFolder
'where
= SwConst.swReorderComponents_LastInFolder
If
Not (selTarget Is Nothing) Then
boolstatus
= myAssem.ReorganizeComponents((vSource),
selTarget)
'
AssemblyDoc ComponentReorganizeNotify event is fired
If
boolstatus = False Then
Debug.Print
"Reorder Component FAILED"
Else
Debug.Print
"Reorder Component SUCCESS"
End
If
End
If
End Sub
Event
Option Explicit
Public WithEvents msrcAssemblyDoc As
SldWorks.AssemblyDoc
Public Function msrcAssemblyDoc_ComponentReorganizeNotify(ByVal
sourceName As String, ByVal targetName As String) As Long
Debug.Print
"msrcAssemblyDoc_ComponentReorganizeNotify"
Debug.Print
"source component is: " & sourceName
Debug.Print
"target component is: " & targetName
msrcAssemblyDoc_ComponentReorganizeNotify
= 1
End Function