MACRO LIBRARY

Get components in selected drawing view

Free public access. No account or subscription required.

Files

Get components in selected drawing view

Code

Module: mMain

'Demonstrates how to get all the components in a selected view.
    
'Preconditions: Drawing is open and view is selected.
'Results: View immediate window.
    
'Notes:
'   This code works with part views, empty views, and section views.
'   If you know that you'll never work with those kinds of views then
'   you can use IView.ReferencedDocument to get IAssemblyDoc sooner.
    
'Written by Keith Rice
'CADSharp LLC
'www.cadsharp.com
    
Sub main()
    Dim swApp As SldWorks.SldWorks
    Dim swModel As ModelDoc2
    Dim swSelMgr As SelectionMgr
    Dim swView As View
    Dim swDrwComp As DrawingComponent
    Dim swComp As Component2
    Dim swCompModel As ModelDoc2
    Dim swAssy As AssemblyDoc
    Dim vComps As Variant
    Dim i As Integer
    
    Set swApp = Application.SldWorks
    Set swModel = swApp.ActiveDoc
    Set swSelMgr = swModel.SelectionManager
    Set swView = swSelMgr.GetSelectedObject6(1, -1)
    Set swDrwComp = swView.RootDrawingComponent
    
    If swDrwComp Is Nothing Then
        Debug.Print "No components in view."
        Exit Sub
    End If
    
    Set swComp = swDrwComp.Component
    
    If swComp Is Nothing Then
        Debug.Print "No components in view because view references a part."
        Exit Sub
    End If
    
    Set swCompModel = swComp.GetModelDoc2
    
    If swCompModel Is Nothing Then
        Debug.Print "Could not access underlying model."
        Exit Sub
    End If
    
    Debug.Print "Components in view:"
    
    If swCompModel.GetType = swDocPART Then
        Debug.Print vbTab & swComp.Name2
    Else
        
        Set swAssy = swCompModel
        vComps = swAssy.GetComponents(False)
        
        For i = 0 To UBound(vComps)
        Set swComp = vComps(i)
            Debug.Print vbTab & swComp.Name2
        Next i
    End If
End Sub