Skip to main content

Run VBA macro automatically on document save using SOLIDWORKS API

This VBA macro handles active document (part, assembly or drawing) save events (including save all and save as) using SOLIDWORKS API and runs a custom code.

Macro operates in the background and needs to be run once a session to start monitoring.

File save command

Configuration

  • Create new macro
  • Place the code from the Macro Module to the default module
  • Add the code which needs to be executed on each save into the OnSaveDocument function
Sub OnSaveDocument(Optional dummy As Variant = Empty)
'TODO: place the code here to run when document is saved
MsgBox "Saved"
End Sub

Macro Module

Entry point which starts events monitoring and handles the code which needs to be run once the save event arrives.

Dim swFileSaveHandler As SaveEventsHandler

Sub main()

Set swFileSaveHandler = New SaveEventsHandler

While True
DoEvents
Wend

End Sub

Sub OnSaveDocument(Optional dummy As Variant = Empty)
'TODO: place the code here to run whn document is saved
MsgBox "Saved"
End Sub

SaveEventsHandler Class Module

Class which handles SOLIDWORKS API save notifications

Dim WithEvents swApp As SldWorks.SldWorks

Private Sub Class_Initialize()
Set swApp = Application.SldWorks
End Sub

Private Function swApp_CommandCloseNotify(ByVal Command As Long, ByVal reason As Long) As Long

Const swCommands_Save As Long = 2
Const swCommands_SaveAll As Long = 19
Const swCommands_SaveAs As Long = 620

If Command = swCommands_Save Or Command = swCommands_SaveAll Or Command = swCommands_SaveAs Then
OnSaveDocument
End If

End Function