MACRO LIBRARY

Save virtual components to external file

Free public access. No account or subscription required.

Instructions

Tool for quickly saving out all selected virtual parts to external files.

Preconditions
virtual parts are selected
Result
virtual parts are saved in same folder as assembly, according to user-specified names

Files

Save virtual components to external file

Code

'Tool for quickly saving out all selected virtual parts to external files
    
'Preconditions: virtual parts are selected
'Results: virtual parts are saved in same folder as assembly, according to _
    user-specified names
    
'Written by Keith Rice
'CADSharp LLC
'www.cadsharp.com
    
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim swAssy As SldWorks.AssemblyDoc
Dim swSelMgr As SldWorks.SelectionMgr
Dim swComp As SldWorks.Component2
Dim i As Integer
Dim strName As String
    
Sub main()
    Set swApp = Application.SldWorks
    Set swModel = swApp.ActiveDoc
    
    If swModel Is Nothing Then
        swApp.SendMsgToUser "Please open an assembly."
        End
    ElseIf swModel.GetType <> swDocASSEMBLY Then
        swApp.SendMsgToUser "Please open an assembly."
        End
    End If
    
    Set swAssy = swModel
    Set swSelMgr = swModel.SelectionManager
    If swSelMgr.GetSelectedObjectCount2(-1) <> 0 Then
        For i = 1 To swSelMgr.GetSelectedObjectCount2(-1)
            If swSelMgr.GetSelectedObjectType3(i, -1) = swSelCOMPONENTS Then
                Set swComp = swSelMgr.GetSelectedObject6(i, -1)
                If swComp.IsVirtual Then
                    strName = InputBox("Please specify a file name for the part " & swComp.Name2 & ".", "Specify file name")
                    If strName <> "" Then
                        swComp.SaveVirtualComponent Left(swModel.GetPathName, InStrRev(swModel.GetPathName, "\")) & strName & ".SLDPRT"
                    Else
                        Exit For
                    End If
                End If
            End If
        Next i
    End If
End Sub
    
'Unfortunately, the InputBox dialog is going to appear behind the SolidWorks application. _
    In order to create a modal input you will need to use a user form in combination with _
    the "Keep x64 user form on top" code provided in www.cadsharp.com/macros
    
'Don't forget that when using IComponent2::IsVirtual, in order to test for True you must use _
    this: "swComp.IsVirtual" not "swComp.IsVirtual = True".