To allow renaming of part and assembly files directly in the FeatureManager tree, enable:
Tools → Options → System Options → FeatureManager
Check the box:
Allow component files to be renamed from the FeatureManager tree
The macro implements:
- Traversing all active assembly levels using GetComponents(False).
- Processing each unique file only once.
- Resolving Lightweight components before renaming.
- Checking for case-insensitive names, including existing files on disk.
- Renaming components using RenameDocument and saving with Save3.
- Separately renaming the root assembly using SaveAs.
- Displaying a list of planned renames and their results in the VBA Immediate window (Ctrl+G).
The macro automatically saves changes to disk. The root assembly is first saved under a new name, then the original file is deleted. This is controlled by the constant:
Private Const REMOVE_OLD_ROOT_AFTER_SAVE_AS As Boolean = True
If False, the original root assembly file will remain on disk.
Components suppressed in all available instances of the active configuration, virtual components, and files missing from disk are not renamed. Other configurations of the root assembly are not processed separately.
External References: The macro maintains references in the processed assembly, but does not search for and update references in closed drawings and other assemblies outside the current tree.
Option Explicit
' Physical file renaming in the active assembly tree.
' Requires SOLIDWORKS 2016 or newer.
' Make a backup of the entire assembly before running.
Private Const REMOVE_OLD_ROOT_AFTER_SAVE_AS As Boolean = True
Public Sub main()
On Error GoTo FatalError
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim swAssy As SldWorks.AssemblyDoc
Dim swComp As SldWorks.Component2
Dim fso As Object
Dim docs As Object, occupied As Object, targets As Object
Dim allComps As Variant, pathKey As Variant
Dim rootPath As String, rootNewPath As String
Dim oldPath As String, oldStem As String, newStem As String
Dim pos As Long, i As Long
Dim changed As Long, failed As Long, skipped As Long
Dim saveErrors As Long, saveWarnings As Long, renameError As Long
Dim ok As Boolean, rootNeedsRename As Boolean
Dim report As String
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
If swModel Is Nothing Then
MsgBox "Open an assembly first.", vbExclamation
Exit Sub
End If
If swModel.GetType <> swDocASSEMBLY Then
MsgBox "The active document is not an assembly.", vbExclamation
Exit Sub
End If
rootPath = swModel.GetPathName
If Len(rootPath) = 0 Then
MsgBox "Save the root assembly before running this macro.", vbExclamation
Exit Sub
End If
Set swAssy = swModel
Set fso = CreateObject("Scripting.FileSystemObject")
If Not fso.FileExists(rootPath) Then
MsgBox "The root assembly file is not found on disk.", vbExclamation
Exit Sub
End If
Set docs = CreateObject("Scripting.Dictionary")
Set occupied = CreateObject("Scripting.Dictionary")
Set targets = CreateObject("Scripting.Dictionary")
docs.CompareMode = vbTextCompare
occupied.CompareMode = vbTextCompare
targets.CompareMode = vbTextCompare
' Resolve lightweight components so that they can be selected/renamed.
swAssy.ResolveAllLightWeightComponents False
' Reserve existing document names across the entire assembly (all folders).
occupied(fso.GetFileName(rootPath)) = True
allComps = swAssy.GetComponents(False)
If IsArray(allComps) Then
For i = LBound(allComps) To UBound(allComps)
Set swComp = allComps(i)
If Not swComp Is Nothing Then
If Not swComp.IsVirtual Then
oldPath = swComp.GetPathName
If Len(oldPath) > 0 Then
occupied(fso.GetFileName(oldPath)) = True
Select Case LCase$(fso.GetExtensionName(oldPath))
Case "sldprt", "sldasm"
If Not swComp.IsSuppressed Then
If Not docs.Exists(oldPath) Then docs.Add oldPath, swComp
End If
End Select
End If
End If
End If
Next i
End If
' Plan names before making any changes to the SOLIDWORKS tree.
For Each pathKey In docs.Keys
oldPath = CStr(pathKey)
oldStem = fso.GetBaseName(oldPath)
pos = InStr(1, oldStem, ";", vbBinaryCompare)
If pos > 0 Then
If fso.FileExists(oldPath) Then
newStem = CleanStem(Left$(oldStem, pos - 1))
targets.Add oldPath, UniqueStem(newStem, _
fso.GetParentFolderName(oldPath), _
"." & fso.GetExtensionName(oldPath), occupied, fso)
Else
skipped = skipped + 1
Debug.Print "SKIP (not found on disk): " & oldPath
End If
End If
Next pathKey
oldStem = fso.GetBaseName(rootPath)
pos = InStr(1, oldStem, ";", vbBinaryCompare)
rootNeedsRename = (pos > 0)
If rootNeedsRename Then
newStem = CleanStem(Left$(oldStem, pos - 1))
newStem = UniqueStem(newStem, fso.GetParentFolderName(rootPath), _
"." & fso.GetExtensionName(rootPath), occupied, fso)
rootNewPath = fso.BuildPath(fso.GetParentFolderName(rootPath), _
newStem & "." & fso.GetExtensionName(rootPath))
End If
If targets.Count = 0 And Not rootNeedsRename Then
MsgBox "Nothing to rename. " & skipped & " inaccessible file(s) skipped.", vbInformation
Exit Sub
End If
Debug.Print String$(65, "-")
Debug.Print "PROPOSED FILE RENAMES:"
For Each pathKey In targets.Keys
Debug.Print "PLAN: " & CStr(pathKey) & " -> " & CStr(targets.Item(pathKey))
Next pathKey
If rootNeedsRename Then Debug.Print "PLAN ROOT: " & rootPath & " -> " & rootNewPath
If MsgBox("Rename " & targets.Count & " component file(s)" & _
IIf(rootNeedsRename, " + root assembly", "") & "?" & vbCrLf & _
"The changes will be SAVED to disk." & vbCrLf & _
"Use a backed-up copy of the project.", _
vbYesNo + vbExclamation, "Rename SOLIDWORKS files") <> vbYes Then Exit Sub
' Rename each distinct component document once (not each instance).
For Each pathKey In targets.Keys
oldPath = CStr(pathKey)
newStem = CStr(targets.Item(oldPath))
Set swComp = docs.Item(oldPath)
swModel.ClearSelection2 True
If swComp.Select4(False, Nothing, False) Then
renameError = swModel.Extension.RenameDocument(newStem)
If renameError = 0 Then
changed = changed + 1
Debug.Print "OK: " & oldPath & " -> " & newStem
Else
failed = failed + 1
Debug.Print "ERROR " & renameError & ": " & oldPath
End If
Else
failed = failed + 1
Debug.Print "ERROR (selection): " & oldPath
End If
Next pathKey
swModel.ClearSelection2 True
' A successful Save3 commits temporary RenameDocument operations to disk.
If changed > 0 Then
saveErrors = 0: saveWarnings = 0
ok = swModel.Save3(swSaveAsOptions_Silent Or swSaveAsOptions_SaveReferenced, _
saveErrors, saveWarnings)
If ok = False Or saveErrors <> 0 Then
MsgBox "Renamed " & changed & " component(s) in memory, but saving FAILED." & vbCrLf & _
"Save error code: " & saveErrors & vbCrLf & _
"Root assembly was NOT renamed. Check references and save manually.", _
vbCritical
Exit Sub
End If
End If
' Root assembly cannot be selected as its own component: use Save As.
If rootNeedsRename Then
saveErrors = 0: saveWarnings = 0
ok = swModel.Extension.SaveAs(rootNewPath, swSaveAsCurrentVersion, _
swSaveAsOptions_Silent, Nothing, _
saveErrors, saveWarnings)
If ok And saveErrors = 0 And fso.FileExists(rootNewPath) Then
Debug.Print "ROOT: " & rootPath & " -> " & rootNewPath
If REMOVE_OLD_ROOT_AFTER_SAVE_AS Then
On Error Resume Next
fso.DeleteFile rootPath, False
If Err.Number <> 0 Then
report = "Old root file could not be deleted: " & rootPath & vbCrLf & _
"Reason: " & Err.Description & vbCrLf
Err.Clear
End If
On Error GoTo FatalError
End If
Else
failed = failed + 1
report = report & "Root Save As failed. Error: " & saveErrors & vbCrLf
End If
End If
report = "Component files renamed: " & changed & vbCrLf & _
"Failed component operations: " & failed & vbCrLf & _
"Skipped (missing): " & skipped & vbCrLf & _
IIf(rootNeedsRename, "Root target: " & rootNewPath & vbCrLf, "") & report & _
vbCrLf & "Details: VBA Immediate window (Ctrl+G)."
MsgBox report, vbInformation, "SOLIDWORKS rename completed"
Exit Sub
FatalError:
MsgBox "Macro error " & Err.Number & ": " & Err.Description & vbCrLf & _
"Some files may already have been renamed. Inspect the assembly.", vbCritical
End Sub
Private Function CleanStem(ByVal stem As String) As String
' Windows filenames may not end with a space or a dot.
Do While Len(stem) > 0
If Right$(stem, 1) <> " " And Right$(stem, 1) <> "." Then Exit Do
stem = Left$(stem, Len(stem) - 1)
Loop
If Len(stem) = 0 Then stem = "EMPT"
CleanStem = stem
End Function
Private Function UniqueStem(ByVal baseName As String, ByVal folder As String, _
ByVal ext As String, ByVal occupied As Object, _
ByVal fso As Object) As String
Dim n As Long, candidate As String, filename As String
n = 0
Do
candidate = baseName
If n > 0 Then candidate = candidate & "-" & CStr(n)
filename = candidate & ext
If Not occupied.Exists(filename) Then
If Not fso.FileExists(fso.BuildPath(folder, filename)) Then Exit Do
End If
n = n + 1
Loop
occupied.Add filename, True
UniqueStem = candidate
End Function
Immediat:
-----------------------------------------------------------------
PROPOSED FILE RENAMES:
PLAN: D:\__TESTS\_TEST_asm_test2\;.SLDPRT -> EMPT
PLAN: D:\__TESTS\_TEST_asm_test2\D1 ; some text1.SLDPRT -> D1
PLAN: D:\__TESTS\_TEST_asm_test2\D2 ; some ; text2;.SLDPRT -> D2
PLAN: D:\__TESTS\_TEST_asm_test2\TestSUAsm ; someAsmtext.SLDASM -> TestSUAsm
PLAN: D:\__TESTS\_TEST_asm_test2\D31 ; some text3.SLDPRT -> D31
PLAN ROOT: D:\__TESTS\_TEST_asm_test2\TestAsm TO ; need for slep.SLDASM -> D:\__TESTS\_TEST_asm_test2\TestAsm TO.SLDASM
OK: D:\__TESTS\_TEST_asm_test2\;.SLDPRT -> EMPT
OK: D:\__TESTS\_TEST_asm_test2\D1 ; some text1.SLDPRT -> D1
OK: D:\__TESTS\_TEST_asm_test2\D2 ; some ; text2;.SLDPRT -> D2
OK: D:\__TESTS\_TEST_asm_test2\TestSUAsm ; someAsmtext.SLDASM -> TestSUAsm
OK: D:\__TESTS\_TEST_asm_test2\D31 ; some text3.SLDPRT -> D31
ROOT: D:\__TESTS\_TEST_asm_test2\TestAsm TO ; need for slep.SLDASM -> D:\__TESTS\_TEST_asm_test2\TestAsm TO.SLDASM