SolidWorks macro to organise segments from an imported dxf/dwg by color on layers

Imagine you get a large dxf or dwg which has been colorized by hand, without using layers. This macro will let you edit the drawing cleanly in SolidWorks, by placing all segments with the same color on specific layers.

'Layerize: SolidWorks macro to organise segments from an imported dxf/dwg by color on layers
'Author  : Ph. Guglielmetti, (c) 2007, e-Systems Consulting Switzerland, all rights reserved
'Licence : you may use this macro for free, as long as this header is kept untouched.
'License : no support is provided, except for e-Systems customers
'Licence : it is forbidden to sell this code or publish it elsewhere without our permission
'Revision: 2007/01/30 PGu for AMBT
'Notes   :
' 1) Don't forget to check "Microsoft Scripting Runtime" in References, needed for the Dictionary object
' 2) This macro is extremely slow if the drawing doc is visible. Minimize it when the macro runs to go faster

Sub main()
    Dim swApp As SldWorks.SldWorks: Set swApp = Application.SldWorks
    Dim doc As SldWorks.DrawingDoc: Set doc = swApp.ActiveDoc
    Dim view As SldWorks.view: Set view = doc.GetFirstView
    Dim sketch As SldWorks.sketch: Set sketch = view.GetSketch
    Dim segs As Variant: segs = sketch.GetSketchSegments
    Debug.Print UBound(segs)
    Dim layermgr As SldWorks.layermgr: Set layermgr = doc.GetLayerManager
    Dim layers As New dictionary
    Dim s As Variant
    For Each s In segs
        Dim seg As SldWorks.SketchSegment: Set seg = s
        Dim c As Long: c = seg.Color
        If Not layers.Exists(c) Then ' create it
            Dim name As String: name = "color " + Str(c)
            Debug.Assert layermgr.AddLayer(name, "created by Layerize macro", seg.Color, seg.Style, seg.Width)
            Call layers.Add(c, name)
            Debug.Print "layer"; name; "created"
        End If
        seg.Layer = layers(c)
        seg.LayerOverride = False
    Next s
    Debug.Print "finished"
End Sub

One Response to “Layers”

  1. 1 jncope

    I love the dictionary object as an alternative to Collections or arrays. It is very under-utilized by VBA developers in my opinion. I am glad to see it in your example.

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: