Site icon BLUE BYTE SYSTEMS INC.

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.

System Requirements

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.

What to Expect?

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

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.

Exit mobile version