Create script to add property in assembly and parts SW 2023

I'm trying to create a VBA macro in SolidWorks to automatically add a custom property called "weight" to my documents (parts and/or assemblies). This property should be linked to the SolidWorks mass property (SW-Mass) so that its value updates automatically.

I've been debugging this issue for a while, and despite simplifying the code as much as possible and checking references, I still get the same error on a specific line. I need your help to understand what could be happening.

The idea is that when I run the macro, SolidWorks will:

Find the name of the active document (e.g., MyPart.SLDPRT or MyAssembly.SLDASM).
Create or update a custom property called "weight."


Property Name: weight
Type: Text
Value/Text Expression: 'SW-Mass@MyDocument.SLDxxx' (with single quotes)
Evaluated Value: (e.g.) 5.34 kg

 

SolidWorks 2023 SP5 

VBA 7.1 

SO: Windows 10

Thanks scriptSolidWorks 

Answers 5
DG
DG 2025-06-19

This is doable, and simple. But I would like to see your current codes first to understand your issue, and then guide you accordingly. 

JS
JS 2025-06-19

You do not need to find the name, this is automatic.  This macro works on Parts and Assemblies.

'by J. R. Sitek
'10-JAN-2023
'This macro adds/sets custom properties
Option Explicit

Sub Main()

Dim swApplication As SldWorks.SldWorks
Dim swModel As ModelDoc2
Dim swFileSaveErrors As swFileSaveError_e
Dim swFileSaveWarnings As swFileSaveWarning_e
Dim vbMaterial As String
Dim vbWeight As String

Set swApplication = Application.SldWorks
Set swModel = swApplication.ActiveDoc

'Add Custom Properties
If swModel.GetType = swDocPART Then
   vbMaterial = Chr(34) & "SW-Material@PART.SLDPRT" & Chr(34)
   vbWeight = Chr(34) & "SW-Mass@PART.SLDPRT" & Chr(34)
   swModel.Extension.CustomPropertyManager("").Add3 "MATERIAL", swCustomInfoText, vbMaterial, swCustomPropertyDeleteAndAdd
   swModel.Extension.CustomPropertyManager("").Add3 "WEIGHT", swCustomInfoText, vbWeight, swCustomPropertyDeleteAndAdd
End If
If swModel.GetType = swDocASSEMBLY Then
   vbWeight = Chr(34) & "SW-Mass@ASM.SLDASM" & Chr(34)
   swModel.Extension.CustomPropertyManager("").Add3 "WEIGHT", swCustomInfoText, vbWeight, swCustomPropertyDeleteAndAdd
End If

'Save document
swModel.Save3 swSaveAsOptions_Silent, swFileSaveErrors, swFileSaveWarnings

End Sub

MJ
MJ 2025-06-19

In principle, you do not need a macro for this. Simply change your template file (e.g. the *.PRTDOT) and add the properties there

comment imagecomment image
FO
FO 2025-06-19

He Luis, you might first want to look for the difference between Mass and Weight. 👍 

DM
DM 2025-06-19

why do you not update the template for this to be there? 
then older parts will eventually get it as you go to fix them.