Run macro on new document creation using SOLIDWORKS API

Edit ArticleEdit Article
More 'Goodies'

Creating new document in SOLIDWORKS
Creating new document in SOLIDWORKS

This VBA macro handles the creation of new document in SOLIDWORKS (part, assembly or drawing) using SOLIDWORKS API and allows to automatically run custom code or another macro when this event happens. This macro will also handle creation of new virtual document in SOLIDWORKS assembly.


  • Create new macro (e.g. RunOnNewDocCreated.swp)
  • Copy the code into corresponding modules of the macro. The VBA macro tree should look similar to the image below:

Macro files tree
Macro files tree

  • Place your code into the main sub of the HandlerModule module. The pointer to IModelDoc2 document is passed as the parameter. Use this pointer instead of ISldWorks::ActiveDoc as new document might not be set to active when this event arrives.
Sub main(model As SldWorks.ModelDoc2)
    'TODO: add your routine here
End Sub

Macro Module

Entry point which starts new document creation events monitoring

Dim swFileNewWatcher As FileNewWatcher

Sub main()
    Set swFileNewWatcher = New FileNewWatcher
    While True
End Sub

FileNewWatcher Class module

Class which handles SOLIDWORKS new document API notifications

Dim WithEvents swApp As SldWorks.SldWorks

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

Private Function swApp_FileNewNotify2(ByVal NewDoc As Object, ByVal DocType As Long, ByVal TemplateName As String) As Long
    HandlerModule.main NewDoc
End Function

HandlerModule module

Custom VBA code which needs to be run for each newly created document

Sub main(model As SldWorks.ModelDoc2)
    'TODO:implement the procedure
    MsgBox "File create: " & model.GetTitle()
End Sub


All articles and code at CodeStack are now open-source and hosted on GitHub. If you want to contribute by modifying existing articles and code snippets, submitting new ones, reporting errors and bugs etc. please follow this blog post for more information. We appreciate any contribution.

Product of Xarial Product of Xarial