US$0.00
0

How to Measure Sketch Length and Add Custom Property Using VBA Macro?

This guide will give you an in-depth idea of a powerful VBA macro for SOLIDWORKS that automates the process to measure sketch length and add custom property using VBA macro.

How to Measure Sketch Length and Add Custom Property Using VBA Macro and An illustration showing two side-by-side screenshots of a "Summary Information" window from a software, labeled "BEFORE" on the left and "AFTER" on the right. Each window has a table with columns for "Property Name," "Type," "Value / Text Expression," and "Evaluated Value," with an "Edit List" button and options for "OK," "Cancel," and "Help." The "BEFORE" table lists properties like MDL_EngAppId, Revision, Description, and a new property, with values such as dates and numbers. The "AFTER" table includes the same properties plus two new ones, "Number" and "Total Length," with updated values, including 10.751 for Total Length, indicating changes or additions to the data.

System Requirements

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

Prerequisites

Before you run the macro, ensure you have the correct file and selection active. The macro will display an error message if these conditions aren’t met.

  • The active document must be a part (.SLDPRT) or an assembly (.SLDASM) file.
  • The sketch you’d like to utilize must be selected within the FeatureManager Design Tree before running the macro.
  • The macro has been designed specifically to ignore construction geometry and text, so your total length calculation is only taken from utilizable geometry.

What to Expect?

After completing the macro, look out for these few things:

  • There will be a new custom property, “Total Length,” in your part or assembly file.
  • Its value will be the total length of your chosen sketch segments, displayed in either inches or millimeters, depending on your document unit settings.
  • If something is wrong—for example, you didn’t select a sketch or you’re in the incorrect type of file—a message box will pop up to tell you what you need to change.

By adding this important metadata, the overall length value can be queried and populated automatically downstream in applications like Bills of Materials (BOMs), drawing title blocks, and Product Data Management (PDM) systems. This keeps the data consistent through the entire project lifecycle, minimizing discrepancies.

Running the Macro

To execute, here’s what you need to do—

  1. Open your SOLIDWORKS part or assembly file.
  2. Locate the sketch you want to measure in the FeatureManager Design Tree.
  3. Click on the sketch to select it. Make sure it is highlighted.
  4. Run the macro. You can do this from the SOLIDWORKS macro toolbar or by going to Tools > Macro > Run… and selecting the macro file.

That’s it! The macro will execute in a split second. won’t see any visual updates in your model, but if you open the Custom Properties of your file, you’ll notice a new property titled “Total Length” with the calculated value.

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

Public Enum swSkchSegments_e
    swSketchLINE = 0
    swSketchARC = 1
    swSketchELLIPSE = 2
    swSketchSPLINE = 3
    swSketchTEXT = 4
    swSketchPARABOLA = 5
End Enum

Sub main()

    ' Declare and initialize necessary SolidWorks objects
    Dim swApp As SldWorks.SldWorks             ' SolidWorks application object
    Dim swModel As SldWorks.ModelDoc2          ' Active document object (part or assembly)
    Dim swSelMgr As SldWorks.SelectionMgr      ' Selection manager object
    Dim swFeat As SldWorks.Feature             ' Feature object for the selected sketch
    Dim swSketch As SldWorks.sketch            ' Sketch object to store the selected sketch
    Dim swCustProp As CustomPropertyManager    ' Custom property manager for adding properties to the model
    Dim swSkchSeg As SldWorks.SketchSegment    ' Sketch segment object for each segment in the sketch
    Dim UserUnit As UserUnit                   ' User unit object to determine the document's unit system
    Dim i As Long                              ' Loop counter for iterating through sketch segments
    Dim bRet As Boolean                        ' Return status of custom property addition
    Dim vSkchSeg As Variant                    ' Array to hold the sketch segments in the selected sketch
    Dim nLength As Double                      ' Total length of the sketch segments

    ' Initialize SolidWorks application and get the active document
    Set swApp = Application.SldWorks
    Set swModel = swApp.ActiveDoc
    
    ' Check if a document is currently active
    If swModel Is Nothing Then
        MsgBox "No active document found. Please open a part or assembly and try again.", vbCritical, "No Active Document"
        Exit Sub
    End If
    
    ' Check if the active document is a part or assembly (skip if it's a drawing)
    If swModel.GetType = 3 Then
        MsgBox "This macro only works on parts or assemblies. Please open a part or assembly and try again.", vbCritical, "Invalid Document Type"
        Exit Sub
    End If
    
    ' Get the user unit system (e.g., metric or imperial)
    Set UserUnit = swModel.GetUserUnit(swUserUnitsType_e.swLengthUnit)
    
    ' Get the selection manager object
    Set swSelMgr = swModel.SelectionManager
    
    ' Check if a sketch is selected in the feature manager
    If swSelMgr.GetSelectedObjectCount2(-1) > 0 And swSelMgr.GetSelectedObjectType3(1, -1) = swSelSKETCHES Then
        ' Get the selected sketch feature
        Set swFeat = swSelMgr.GetSelectedObject5(1)
        Set swSketch = swFeat.GetSpecificFeature2
        ' Get all the sketch segments in the selected sketch
        vSkchSeg = swSketch.GetSketchSegments
        
        ' Loop through each segment in the sketch
        For i = 0 To UBound(vSkchSeg)
            Set swSkchSeg = vSkchSeg(i)
            ' Ignore construction lines and text segments
            If swSkchSeg.ConstructionGeometry = False Then
                If swSketchTEXT <> swSkchSeg.GetType Then
                    ' Accumulate the length of valid sketch segments
                    nLength = nLength + swSkchSeg.GetLength
                End If
            End If
        Next i

        ' Clear any selections in the document
        swModel.ClearSelection2 True

        ' Get the custom property manager object for the active document
        Set swCustProp = swModel.Extension.CustomPropertyManager("")

        ' Add the total length as a custom property in inches or mm based on the unit system
        If UserUnit.IsMetric = False Then
            bRet = swCustProp.Add3("Total Length", 30, Round(nLength * 39.3701, 2) & " in", 1) ' Add total length in inches
        ElseIf UserUnit.IsMetric Then
            bRet = swCustProp.Add3("Total Length", 30, Round(nLength * 1000, 2) & " mm", 1) ' Add total length in mm
        End If
        
    Else
        ' Show error message if no sketch is selected
        MsgBox "Please select a sketch from the feature manager and try again.", vbExclamation, "No Sketch Selected"
        Exit Sub
    End If

End Sub

You can download the macro from here.

Need a Customized SOLIDWORKS Solution?

If you need a customized version of the measure sketch length and add custom property using VBA macro or more advanced automation solutions, make sure to reach out! Our experts at Blue Byte System Inc. will provide you with a custom macro that is best suited to your specific needs. Contact us today to learn how we can help you streamline your engineering processes and maximize your productivity.

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
    ×