Option Explicit
' Macro to split filename and assign to custom properties
' Drawing Number: First 13 or 14 characters depending on hyphen
' Drawing Name: Remaining part of the filename
Sub main()
Dim swApp As Object
Dim swModel As Object
Dim swCustProp As Object
Dim swConfig As Object
Dim fileName As String
Dim drawingNumber As String
Dim drawingName As String
Dim splitPosition As Integer
' Connect to SolidWorks
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
' Check if a document is open
If swModel Is Nothing Then
MsgBox "Please open a document first.", vbExclamation
Exit Sub
End If
' Get the filename without path and extension
fileName = GetFilenameWithoutExtension(swModel.GetPathName)
' Check if filename is long enough to process
If Len(fileName) < 14 Then
MsgBox "Filename is too short. Must be at least 14 characters.", vbExclamation
Exit Sub
End If
' Determine split position based on your rule
If Mid(fileName, 14, 1) = "-" Then
splitPosition = 13
Else
splitPosition = 14
End If
' Split the filename
drawingNumber = Left(fileName, splitPosition)
' Check if there are characters after the split position
If Len(fileName) > splitPosition Then
' If the split was due to a hyphen, skip the hyphen character
If Mid(fileName, 14, 1) = "-" Then
drawingName = Mid(fileName, splitPosition + 2) ' +2 to skip the hyphen and space after it
Else
drawingName = Mid(fileName, splitPosition + 1) ' +1 to start from the next character
End If
Else
drawingName = ""
End If
' Get the custom property manager
Set swCustProp = swModel.Extension.CustomPropertyManager("")
' Set the custom properties
swCustProp.Set2 "Drawing Number", drawingNumber
swCustProp.Set2 "Drawing Name", drawingName
' Inform the user
MsgBox "Custom properties updated:" & vbCrLf & _
"Drawing Number: " & drawingNumber & vbCrLf & _
"Drawing Name: " & drawingName, vbInformation
' Force a rebuild to update the drawing
swModel.ForceRebuild3 True
End Sub
' Function to extract filename without extension
Function GetFilenameWithoutExtension(ByVal fullPath As String) As String
Dim fileName As String
Dim lastBackslash As Integer
Dim lastDot As Integer
' Find the last backslash and dot in the path
lastBackslash = InStrRev(fullPath, "\")
lastDot = InStrRev(fullPath, ".")
' Extract the filename without extension
If lastBackslash > 0 And lastDot > lastBackslash Then
fileName = Mid(fullPath, lastBackslash + 1, lastDot - lastBackslash - 1)
ElseIf lastBackslash > 0 Then
fileName = Mid(fullPath, lastBackslash + 1)
Else
fileName = fullPath
End If
GetFilenameWithoutExtension = fileName
End Function