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.
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
To simplify this function you can call another macro without explicitly copying the code. Explore the Run Group Of Macros example.
Add new Class Module and name it SaveEventsHandler. Paste the code from the SaveEventsHandler Class Module
It might be useful to automatically run this macro with each session of SOLIDWORKS. Follow the Run SOLIDWORKS macro automatically on application start link for more information.
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