US$0.00
0

The VBA Macro to Automate Sketch Editing in SOLIDWORKS

Description

This macro for SOLIDWORKS automates a repetitive and frequent task for engineers: changing and exiting sketches. Following the provided code, it is capable of automatically determining and adjusting the view to normal for an active sketch or exiting the sketch if the view is already normal. Also, when to open a sketch, when to normalize a view, and when to exit from the sketch is needed. The macro can also deal with suppressed subcomponents automatically, as well as navigate complex feature trees. This makes a VBA macro to automate sketch editing in SOLIDWORKS a potent addition to your design process and productivity.

VBA Macro to Automate Sketch Editing in SOLIDWORKS and An illustration of a person working at a computer, with hands on a keyboard and mouse. The computer screen displays a 3D model of a mechanical part with a hole, viewed in a design software interface showing tools like "Pains," "Origine," "Extrusion," and "Add Step" on the left sidebar. An orange gear icon with a small robot face overlays the screen, symbolizing automation or AI assistance in the design process.

System Requirements

  • SOLIDWORKS Version: SOLIDWORKS 2014 or newer
  • Operating System: Windows 7 or later

Pre-Conditions

  • Active Document: An active part (.sldprt) or assembly (.sldasm) document must be open in SOLIDWORKS.
  • Selection: For the macro to operate correctly, a feature, face, edge, or sketch must be selected.

Results

  • Automated View & Sketch Access: Edits the driving sketch of the selected feature/geometry, while also orienting the view normal to the sketch plane.
  • Efficient Sketch Exits: Exits from the active sketch if the view is already oriented normal, streamlining the completion of a sketching session.
  • Component & Hierarchy Handling: Automatically resolves the selected subcomponents and navigates into the selected sketch hierarchy of more complex features, ensuring a seamless operation.

Process to Implement the Macro

  1. Execute the Macro: Execute the macro in an open SOLIDWORKS document. The associated document must be a valid document type (part or assembly), and the appropriate items must be selected.
  2. Behavior Based on Selection:

โ—‹        If the user has selected a feature or geometry, the macro will open the driving sketch and view the model in a different view.

โ—‹        If no entities are selected and the user is in an active sketch, the macro will set the view to normal.

โ—‹        If the user is already viewing in a normal view, the macro will exit the sketch and end.

VBA Macro Code

' Disclaimer:
' The code provided should be used at your own risk.  
' Blue Byte Systems Inc. assumes no responsibility for any issues or damages that may arise from using or modifying this code.  
' For more information, visit [Blue Byte Systems Inc.](https://bluebyte.biz).

Option Explicit

' Define a structure for storing view data
Type ViewData
    ViewScale As Double                           ' Scale of the view
    Orientation As SldWorks.MathTransform         ' Orientation transformation matrix
    Translation As SldWorks.MathVector            ' Translation vector
End Type

' Enum for comparison results between two views
Enum CompareViewResult_e
    Same = 0                                      ' Views are identical
    DiffOrientation = 2 ^ 0                       ' Different orientations
    difftranslation = 2 ^ 1                       ' Different translations
    diffscale = 2 ^ 2                             ' Different scales
End Enum

' Debugging constants and tolerance
Const Bug As Boolean = False                      ' Debug output flag
Const Tol As Integer = 2                          ' Tolerance for comparisons

Sub main()
    On Error Resume Next

    Dim swApp As SldWorks.SldWorks
    Dim swDoc As SldWorks.ModelDoc2
    Dim SelMgr As SldWorks.SelectionMgr
    Dim swFeat As SldWorks.Feature
    Dim swSelType As Long
    Dim StartView As ViewData
    Dim CurView As ViewData
    Dim compRes As CompareViewResult_e

    ' Initialize SolidWorks objects
    Set swApp = Application.SldWorks
    Set swDoc = swApp.ActiveDoc
    Set SelMgr = swDoc.SelectionManager
    StartView = GetViewData(swDoc.ActiveView)

    ' Check if a sketch is active
    If Not swDoc.GetActiveSketch2 Is Nothing Then
        ' No selection: Align view "normal to" the sketch
        If SelMgr.GetSelectedObjectCount2(-1) < 1 Then
            swDoc.ShowNamedView2 "*Normal To", -1
            CurView = GetViewData(swDoc.ActiveView)
            compRes = CompareViewData(StartView, CurView, Tol)
            If compRes = Same Then
                swDoc.SketchManager.InsertSketch True
                Exit Sub
            End If
        Else
            swDoc.SketchManager.InsertSketch True
        End If
    End If

    ' Resolve selected feature or entity
    swSelType = SelMgr.GetSelectedObjectType3(1, -1)
    Select Case swSelType
        Case swSelFACES, swSelEDGES
            Set swFeat = SelMgr.GetSelectedObject6(1, -1).GetFeature
            If swFeat Is Nothing Then Exit Sub
        Case swSelBODYFEATURES, swSelSKETCHES
            Set swFeat = SelMgr.GetSelectedObject6(1, -1)
        Case Else
            Exit Sub
    End Select

    ' Edit sketch or feature
    If swFeat.GetTypeName = "ProfileFeature" Then
        swDoc.EditSketchOrSingleSketchFeature
    Else
        swDoc.FeatEdit
    End If

    ' Align view to "normal to" if a sketch is active
    If Not swDoc.GetActiveSketch2 Is Nothing Then
        swDoc.ShowNamedView2 "*Normal To", -1
    End If

    ' Clear selections
    swDoc.ClearSelection2 True
End Sub

' Function to get view data (scale, orientation, translation)
Private Function GetViewData(view As SldWorks.ModelView) As ViewData
    Dim data As ViewData
    Set data.Orientation = view.Orientation3       ' Get orientation matrix
    Set data.Translation = view.Translation3       ' Get translation vector
    data.ViewScale = view.Scale2                   ' Get view scale
    GetViewData = data
End Function

' Function to compare two sets of view data
Private Function CompareViewData(firstViewData As ViewData, secondViewData As ViewData, Tol As Integer) As CompareViewResult_e
    Dim res As CompareViewResult_e
    res = Same

    ' Compare orientation
    If Not CompareArrays(firstViewData.Orientation.ArrayData, secondViewData.Orientation.ArrayData, Tol) Then
        res = res + DiffOrientation
    End If

    ' Compare translation
    If Not CompareArrays(firstViewData.Translation.ArrayData, secondViewData.Translation.ArrayData, Tol) Then
        res = res + difftranslation
    End If

    ' Compare scale
    If Not TolerantEqual(firstViewData.ViewScale, secondViewData.ViewScale, Tol) Then
        res = res + diffscale
    End If

    CompareViewData = res
End Function

' Function to compare arrays with tolerance
Private Function CompareArrays(firstArr As Variant, secondArr As Variant, Tol As Integer) As Boolean
    If UBound(firstArr) = UBound(secondArr) Then
        Dim i As Integer
        For i = 0 To UBound(firstArr)
            If Not TolerantEqual(firstArr(i), secondArr(i), Tol) Then
                CompareArrays = False
                Exit Function
            End If
        Next
        CompareArrays = True
    Else
        CompareArrays = False
    End If
End Function

' Function to compare two numbers with tolerance
Private Function TolerantEqual(a As Variant, b As Variant, Tol As Integer) As Boolean
    TolerantEqual = Abs(a - b) <= Abs(a / 10 ^ Tol) ' Compare within tolerance
End Function

Macro

You can download the macro from here.

Customization of The Macro

For engineering teams who have special workflow requirements, please reach out, and we will be sure to provide you with our modified version to meet your immediate needs. Regardless of your level of customization needs to maximize your design process, we can help!

Custom development of SOLIDWORKS macros and add-ins is our specialty at Blue Byte Systems Inc. However, we also specialize in seamless integration with existing systems, specific file types or multi-body part tasks are always in mind.

Please contact us to discuss how we can help you reach a more efficient and productive workflow with our custom solutions.

Author

Amen Jlili

Amen Jlili is the founder and technical director of Blue Byte Systems Inc., a software company in Vancouver, Canada, specializing in automating SOLIDWORKS and PDM. With over a decade of experience, he has authored several courses and open-source frameworks related to the SOLIDWORKS API. His leadership ensures that Blue Byte Systems prioritizes customer satisfaction and delivers high-quality software and CAD design solutions.
0
    0
    Your Cart
    Your cart is emptyReturn to Shop
    ×