US$0.00
0

SOLIDWORKS API: Automate File Naming from Custom Properties

Use the SOLIDWORKS API to automate file naming from custom properties: read values, build a valid name, Save As safely, and handle it in PDM.
SOLIDWORKS API: Automate File Naming from Custom Properties
Picture of Amen Jlili

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.

To automate file naming from custom properties with the SOLIDWORKS API, read the property values through ICustomPropertyManager (using Get6 for the resolved value), build a file name string from them, clean out characters Windows does not allow, and save the document under the new name with IModelDocExtension.SaveAs. The catch is references: saving a part under a new name does not update assemblies and drawings that are closed, so for existing files you either rename with Pack and Go or, in a vault, let SOLIDWORKS PDM do the rename. In SOLIDWORKS PDM the better pattern is often the reverse: generate the number with a serial number and let data card variables push it into the custom properties.

Below we cover both approaches, with a working VBA macro.

Prefer no code at all? This short video shows how to customize output filenames in PDMPublisher without writing a macro.

How custom properties work in the API

The CustomPropertyManager

Every document exposes custom properties through ICustomPropertyManager. You get it from the document’s extension:

Set swPropMgr = swModel.Extension.CustomPropertyManager(configName)

The members you will use most:

Member Purpose
Get6 Read a property. Returns the raw value (which may be an expression) and the resolved value, plus flags for whether it was resolved and whether it is linked
Add3 Create a property, with an option that controls what happens if it already exists
Set2 Change the value of an existing property
Delete2 Remove a property
GetNames List all property names

These numbered versions replaced older members such as Get5 and Add2. If you are unsure which version to use, check the Availability section in the API Help for your oldest supported release.

File-level vs configuration-specific properties

This is where most naming macros go wrong.

  • File-level properties live on the Custom tab of the Summary Information dialog. Pass an empty string "" as the configuration name.
  • Configuration-specific properties live on the Configuration Specific tab. Pass the configuration name.

A part can have a PartNumber at file level and a different PartNumber in each configuration. Your naming rule has to say which one wins. Our usual rule: read the configuration-specific value for the active configuration first, and fall back to the file-level value if it is empty. That matches how many BOM setups resolve properties, and it means a macro behaves the same way your drawings and BOM tables do.

Also read the resolved value, not the raw value. A property like Material often contains an expression such as "SW-Material@Part1.SLDPRT". The raw text is useless in a file name; the resolved value (AISI 304, for example) is what you want.

Building a file name from properties

A naming rule is a template. For example:

{PartNumber}_{Revision}_{Description}.SLDPRT

Before you write code, decide:

  1. Which properties are mandatory. If PartNumber is empty, stop and tell the user. Never save a file called _A_.SLDPRT.
  2. How to sanitize values. Windows file names cannot contain \ / : * ? " < > |. Descriptions often contain " (inches) or /. Replace them with a safe character.
  3. Length limits. Long descriptions combined with deep folders can exceed path length limits. Truncate the description part.
  4. Collisions. If the target file already exists, do not overwrite it silently.

SaveAs with IModelDocExtension.SaveAs

IModelDocExtension.SaveAs saves the active document under a new path and returns True or False, with error and warning codes as output parameters. Use swSaveAsOptions_Silent so no dialogs appear, and check the error code against swFileSaveError_e if it fails.

Note what a Save As actually does: the open document now points to the new file, and the old file stays on disk. Any assembly or drawing that is open in the same session and references the part will reference the new name once you save it. Assemblies and drawings that are closed still reference the old file name. That is fine for a brand new part, and a problem for an existing one.

Automate file naming from custom properties: a VBA macro

This macro builds a name from PartNumber, Revision and Description, sanitizes it, and saves the active part or assembly into the same folder. (Drawings have no active configuration, so the macro stops on them.)

Option Explicit

Function ReadProp(mgr As SldWorks.CustomPropertyManager, propName As String) As String
    Dim valOut As String, resolved As String
    Dim wasResolved As Boolean, linked As Boolean
    mgr.Get6 propName, False, valOut, resolved, wasResolved, linked
    ReadProp = Trim(resolved)
End Function

Function CleanName(s As String) As String
    Dim bad As Variant, c As Variant
    bad = Array("\", "/", ":", "*", "?", """", "<", ">", "|")
    For Each c In bad
        s = Replace(s, c, "-")
    Next
    CleanName = Left(s, 60)
End Function

Sub main()
    Dim swApp As SldWorks.SldWorks
    Dim swModel As SldWorks.ModelDoc2
    Dim cfgName As String, pn As String, rev As String, desc As String
    Dim folder As String, ext As String, newPath As String
    Dim errs As Long, warns As Long

    Set swApp = Application.SldWorks
    Set swModel = swApp.ActiveDoc
    If swModel Is Nothing Then MsgBox "Open a document first.": Exit Sub
    If swModel.GetPathName = "" Then MsgBox "Save the document once first.": Exit Sub
    If swModel.GetType = swDocumentTypes_e.swDocDRAWING Then MsgBox "Run this on a part or assembly.": Exit Sub

    cfgName = swModel.ConfigurationManager.ActiveConfiguration.Name
    pn = ReadProp(swModel.Extension.CustomPropertyManager(cfgName), "PartNumber")
    If pn = "" Then pn = ReadProp(swModel.Extension.CustomPropertyManager(""), "PartNumber")
    rev = ReadProp(swModel.Extension.CustomPropertyManager(""), "Revision")
    desc = ReadProp(swModel.Extension.CustomPropertyManager(""), "Description")

    If pn = "" Then MsgBox "PartNumber is empty.": Exit Sub

    folder = Left(swModel.GetPathName, InStrRev(swModel.GetPathName, "\"))
    ext = Mid(swModel.GetPathName, InStrRev(swModel.GetPathName, "."))
    newPath = folder & CleanName(pn & "_" & rev & "_" & desc) & ext

    If Dir(newPath) <> "" Then MsgBox "File already exists: " & newPath: Exit Sub

    If swModel.Extension.SaveAs(newPath, swSaveAsVersion_e.swSaveAsCurrentVersion, _
            swSaveAsOptions_e.swSaveAsOptions_Silent, Nothing, errs, warns) Then
        MsgBox "Saved as " & newPath
    Else
        MsgBox "Save As failed, error code " & errs
    End If
End Sub

Set references to the SOLIDWORKS type library and constant type library in Tools > References so the enum names resolve. For a more complete tool with a form, see our custom properties and Save As macro, and for property basics, how to measure sketch length and add a custom property using VBA.

Tip: run naming macros on new files before they are used in assemblies. Renaming is cheap at birth and expensive later.

Renaming referenced files needs care

If the part already appears in assemblies and drawings, a Save As leaves the parents pointing at the old name. You have three safer options:

Method Updates references Best for
Pack and Go Yes, within the set you pack Copying or renaming a whole assembly and its drawings outside PDM
SOLIDWORKS PDM rename Yes, for references tracked in the vault Any file already checked in to a vault
Save As on new, unreferenced files Nothing to update New parts before they are used

Pack and Go is available through the API too: IModelDocExtension.GetPackAndGo returns an IPackAndGo object where you can set new file names for each document in the set and save. It is the right tool when you are renaming an assembly structure outside a vault, but plan for drawings (include them in the set) and test on a copy first. Using a custom property as a file name prefix or suffix during Pack and Go is a question that has come up on CADOverflow.

What you should not do is rename files in Windows Explorer and hope SOLIDWORKS finds them. It will not, and you end up with missing references the next time someone opens the assembly.

In SOLIDWORKS PDM: serial numbers and data card variables

If your files live in SOLIDWORKS PDM, flip the problem around. Instead of naming files from properties after the fact, let the vault generate the number and keep names and properties in sync.

Serial numbers

A PDM serial number generates the next number from a counter with a format you define (prefix, padding, and so on). Assigned as the default value of a data card control, it fills in the part number when a new file is added. Serial numbers can also drive file names when new files are created from PDM templates. We explain why sequential numbering also keeps a vault healthy in why serial numbers and folder number ranges keep your SOLIDWORKS PDM vault fast.

Variables mapped to custom properties

A PDM variable is linked to the file’s custom properties through its attributes. For SOLIDWORKS files, the CustomProperty block with the property name as the attribute maps the variable to that custom property. The attribute settings also control which configurations the mapping applies to. When a user fills in the data card, PDM writes the value into the file’s custom property; when the file’s property changes in SOLIDWORKS, PDM reads it back on check in.

That gives you a clean pipeline:

  1. User saves a new part into the vault.
  2. The data card fills PartNumber from a serial number.
  3. The variable mapping writes PartNumber into the SOLIDWORKS custom property.
  4. Drawings, BOMs and exports read the same property.

Renaming in the vault

When a file is already in the vault and its number must change, use the PDM rename command (or IEdmFile5.Rename from the API) rather than a SOLIDWORKS Save As. The vault knows the where-used relationships and keeps parent references intact, which is precisely what Save As cannot do for closed files. Remember that writing custom properties or card variables requires the file to be checked out, and that variable changes should always go through the PDM client or API, never through direct SQL updates.

If you are automating this at scale, for example renaming hundreds of legacy files from their card values during a cleanup, a script is easier to audit than a one-off macro. PDMShell lets PDM administrators script vault operations from the command line, which is how we handle many of these bulk jobs for customers. For the full range of options, see things you can do with the SOLIDWORKS PDM API.

Community discussions

FAQ

Should I use file-level or configuration-specific properties for the file name?

Pick one rule and apply it everywhere. A common rule is: read the active configuration’s value and fall back to the file-level value if it is empty. Make sure your BOMs and drawing templates use the same rule.

Why does my assembly show missing parts after I renamed a part with a macro?

Save As only updates references in documents open in the same session. Closed assemblies and drawings still point to the old name. Use Pack and Go or a PDM rename for files that are already referenced.

Can PDM name the file automatically from a serial number?

PDM serial numbers can fill data card values when files are added and can drive file names for files created from PDM templates. Map the card variable to a custom property so the number appears in SOLIDWORKS too.

Is Get6 required, or can I keep using older Get methods?

Older versions such as Get5 still work, but Get6 is the current member and also tells you whether the value is linked to another property. Use it for new code if your oldest supported release has it.

Need help with this?

If you need a naming macro, a property cleanup or a vault-wide rename done safely, contact us. For scripted bulk work in SOLIDWORKS PDM, start with a PDMShell trial.

Need this adapted to your workflow?

We build custom SOLIDWORKS macros, add-ins and PDM automation.

Picture of Amen Jlili

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.
0
0
Your Cart
Your cart is emptyReturn to Shop