CN¥0.00
0

SOLIDWORKS VBA for Beginners: Write Your First Macro

Learn SOLIDWORKS VBA from scratch: record vs write, the VBA editor, swApp and ActiveDoc, and a first macro that reads and writes custom properties.
SOLIDWORKS VBA for Beginners: Write Your First Macro
Picture of Amen Jlili

Amen Jlili

Amen Jlili is the founder and technical director of Blue Byte Systems Inc., a software company in Vancouver, Canada, specializing in automating SOLIDWORKS and PDM.

SOLIDWORKS VBA is the Visual Basic for Applications editor built into SOLIDWORKS, and it is the quickest way to start writing macros for SOLIDWORKS. You open it from Tools > Macro > New, get a reference to the application (swApp) and the active document (ActiveDoc), and call the SOLIDWORKS API to do what you would otherwise click through by hand. In Part 1 of our beginner series, we write a real macro that reads and writes a custom property, add proper error checks, switch to early binding, and put the macro on a toolbar button.

You do not need to be a programmer to follow along. If you can write an Excel formula and you know SOLIDWORKS well, you have most of what you need.

Why SOLIDWORKS VBA is still the right place to start

There are other languages for SOLIDWORKS automation (VB.NET and C# among them, which we compare in our beginner’s guide to SOLIDWORKS programming languages). VBA is still where we tell everyone to start, for practical reasons:

  • It ships with SOLIDWORKS. Nothing to install.
  • The macro recorder writes VBA, so you can learn by recording.
  • Macros run in process, so they are fast for small tasks.
  • A .swp file is easy to share: copy it, run it.

The trade-offs show up later: VBA is harder to version control, has limited UI options, and is not ideal for large projects. Part 2 of this series covers moving to C# when you hit those limits.

Recording vs writing macros

Recording

Tools > Macro > Record captures your actions as VBA. Stop the recording, save it, then open it with Tools > Macro > Edit. Recorded code is useful for discovering which API calls correspond to a command. For example, record yourself inserting a fillet and you will find a call that creates the feature.

Writing

Recorded macros have problems that make them fragile:

  • They hard code selections by coordinates or names, so they break on another model.
  • They declare everything As Object, so there is no IntelliSense.
  • They often contain calls you do not need (view changes, redundant selections).
  • They sometimes use older, obsolete versions of API methods.

Our approach: record to find the call, then write the macro yourself using the API Help. The recorder is a search tool, not an author.

A tour of the VBA editor

Create a new macro with Tools > Macro > New, save the .swp file somewhere sensible (a shared macros folder is a good habit), and the VBA editor opens. The parts you will use:

Area What it is for
Project Explorer Lists modules, forms and classes in the macro
Code window Where you write code; the generated module contains Sub main()
Immediate window (Ctrl+G) Print values with Debug.Print and test expressions
Object Browser (F2) Browse every SOLIDWORKS interface, method and enum
Tools > References Type libraries used for early binding

Useful keys: F5 runs the macro, F8 steps one line at a time, F9 sets a breakpoint. Stepping with F8 while watching values in the Immediate window teaches you more about the API than any amount of reading.

swApp and ActiveDoc: the two objects every macro starts with

Every SOLIDWORKS macro begins the same way:

Dim swApp As Object
Set swApp = Application.SldWorks

swApp is the SOLIDWORKS application, the ISldWorks interface in the API Help. From it you reach everything else. The most used member is ActiveDoc, which returns the document in the active window as an IModelDoc2, or Nothing if no document is open.

IModelDoc2 is the common interface for parts, assemblies and drawings. Its GetType method tells you which one you have, and its Extension property returns IModelDocExtension, where many newer API members live, including custom properties.

Your first SOLIDWORKS VBA macro: read and write a custom property

Our goal: read the Description custom property of the active document, show it, and set a CheckedBy property to the current Windows user name.

Custom properties are handled by ICustomPropertyManager, which you get from ModelDoc2.Extension.CustomPropertyManager(configName). Pass an empty string for file-level properties (the Custom tab) or a configuration name for configuration-specific ones.

Option Explicit

Sub main()
    Dim swApp As SldWorks.SldWorks
    Dim swModel As SldWorks.ModelDoc2
    Dim swPropMgr As SldWorks.CustomPropertyManager
    Dim valOut As String
    Dim resolvedVal As String
    Dim wasResolved As Boolean
    Dim linkToProp As Boolean
    Dim ret As Long

    Set swApp = Application.SldWorks
    Set swModel = swApp.ActiveDoc

    If swModel Is Nothing Then
        MsgBox "Please open a part, assembly or drawing first.", vbExclamation
        Exit Sub
    End If

    ' Empty string = file-level properties (Custom tab)
    Set swPropMgr = swModel.Extension.CustomPropertyManager("")

    ' Read Description
    ret = swPropMgr.Get6("Description", False, valOut, resolvedVal, wasResolved, linkToProp)
    If resolvedVal = "" Then
        MsgBox "This document has no Description.", vbInformation
    Else
        MsgBox "Description: " & resolvedVal, vbInformation
    End If

    ' Write CheckedBy, replacing any existing value
    ret = swPropMgr.Add3("CheckedBy", swCustomInfoType_e.swCustomInfoText, _
                         Environ("USERNAME"), _
                         swCustomPropertyAddOption_e.swCustomPropertyReplaceValue)

    If ret <> swCustomInfoAddResult_e.swCustomInfoAddResult_AddedOrChanged Then
        MsgBox "Could not write CheckedBy (code " & ret & ").", vbExclamation
        Exit Sub
    End If

    swModel.SetSaveFlag
    MsgBox "CheckedBy set to " & Environ("USERNAME"), vbInformation
End Sub

What the code does

  • Get6 returns the raw value (valOut), which may contain an expression like "SW-Mass@Part1.SLDPRT", and the evaluated value (resolvedVal). For display you almost always want the resolved value.
  • Add3 creates the property, and the last argument decides what to do if it already exists. swCustomPropertyReplaceValue updates the value in place; swCustomPropertyOnlyIfNew leaves an existing value alone.
  • SetSaveFlag marks the document as modified so the user is prompted to save. The macro does not save on its own, which is a safe default for a beginner macro.

For a longer, real-world example that combines properties with saving, see the custom properties and Save As macro.

Error checks every macro needs

Most macro crashes come from three causes. Guard against all three from day one.

  1. No document open. ActiveDoc returns Nothing. Check it before using it, as above.
  2. Wrong document type. A macro written for parts will fail on a drawing. Check swModel.GetType against swDocumentTypes_e.swDocPART, swDocASSEMBLY or swDocDRAWING.
  3. Ignored return values. Many API calls do not raise errors; they return False, Nothing or an error code. Read the return value and compare it to the enumeration in the API Help.

You can also add a simple error handler so the user sees a clear message instead of a VBA crash dialog:

Sub main()
    On Error GoTo Failed
    ' ... macro code ...
    Exit Sub
Failed:
    MsgBox "Macro failed: " & Err.Description, vbCritical
End Sub

Use On Error GoTo for unexpected failures, not as a replacement for checking return values.

Early binding: set your references

The macro above declares swApp As SldWorks.SldWorks instead of As Object. That is early binding, and it needs references to the SOLIDWORKS type libraries. In the VBA editor go to Tools > References and make sure these are checked:

  • SldWorks 20xx Type Library (the year matches your SOLIDWORKS version)
  • SOLIDWORKS 20xx Constant type library

With early binding you get IntelliSense, compile-time checks (Debug > Compile), and readable enum names like swDocPART instead of magic numbers. When a macro opens in a newer SOLIDWORKS version, VBA usually updates these references automatically. If you see “MISSING:” in front of a reference, uncheck it and check the current version. Our article on early binding vs late binding covers the details and edge cases.

Running your macro from a button or shortcut

Running from Tools > Macro > Run gets old quickly. Put the macro on a toolbar:

  1. Go to Tools > Customize and open the Commands tab.
  2. Select the Macro category.
  3. Drag the New Macro Button onto any toolbar or the CommandManager.
  4. In the dialog, browse to your .swp file, pick the module and the main procedure, and optionally set a tooltip and icon.

Once the button exists, you can assign a keyboard shortcut to it from the Keyboard tab of the same Customize dialog by searching for your macro’s name. A shortcut such as Ctrl+Shift+P for a “set properties” macro quickly becomes muscle memory. For a full example with a toolbar button, see our save drawing as PDF macro with toolbar integration.

Tip: keep shared macros in one network folder and point everyone’s buttons there. When you fix a bug, everyone gets the fix the next time they run it.

Next steps

Once your first macro works, build on it in small steps:

  • Loop through all configurations with swModel.GetConfigurationNames and write configuration-specific properties.
  • Use a UserForm to collect values instead of hard coding them.
  • Traverse an assembly and update properties on every component.
  • Save or export the document after updating it.

Our SOLIDWORKS VBA macros library has free, working macros you can open and study, from exporting sketches to cleaning up drawings; reading working code is one of the best ways to learn. CADOverflow also has a list of the most requested/downloaded VBA macros. For more background on what macros can automate, see how to use VBA macros for SOLIDWORKS automation.

In Part 2, we take this same logic into C# and build a SOLIDWORKS add-in, which is the natural next step when your macros grow beyond a single file.

Community discussions

FAQ

Do I need to install anything to write SOLIDWORKS VBA macros?

No. The VBA editor is included with SOLIDWORKS. Open it with Tools > Macro > New or Tools > Macro > Edit.

What is the difference between a .swp and a .swb macro?

A .swp file is a VBA project and is what you should use. A .swb file is a plain text macro format from older releases; it lacks the editor, debugger and forms.

Can a SOLIDWORKS VBA macro run without SOLIDWORKS open?

No. A VBA macro runs inside SOLIDWORKS. To work with files without SOLIDWORKS, you need a standalone program or the Document Manager API.

Why does my recorded macro fail on a different model?

Recorded macros usually select entities by name or screen position. Those names and positions differ between models. Rewrite the selection logic using the API instead.

Need help with this?

If you want your team trained on SOLIDWORKS VBA or need a macro written for your process, contact us. You can also browse the free macro library for ready-made starting points.

Rather not write VBA for everyday jobs? PDMPublisher for SOLIDWORKS handles batch exports, property updates and assembly copies with no code, and its Publisher Macros let you add your own VBA when you need it. Start a free 7-day trial.

Need this adapted to your workflow?

We build custom SOLIDWORKS macros, add-ins and PDM automation.

Picture of Amen Jlili

Amen Jlili

Amen Jlili is the founder and technical director of Blue Byte Systems Inc., a software company in Vancouver, Canada, specializing in automating SOLIDWORKS and PDM.
0
0
Your Cart
Your cart is emptyReturn to Shop