Design Automation with SolidWorks Macros: A VBA Guide



A SolidWorks macro is a powerful tool that automates repetitive design operations and multiplies an engineer’s productivity. If you repeat the same steps every day, you can write a SolidWorks macro and complete that process in seconds. In this guide we take a detailed look at the fundamentals of SolidWorks VBA macro programming, along with practical examples from the sheet metal field.

What Is a SolidWorks Macro and What Does It Do?

This tool consists of automation scripts written using the SolidWorks API. They are written in VBA (Visual Basic for Applications) and saved with the .swp extension. Macros can be recorded via Tools > Macro > Record on the menu bar, or written from scratch.

The greatest advantage of macros is that they automate repetitive operations. Imagine repeating the same 15 steps in every design. If that operation is performed 10 times a day, you spend roughly 625 hours a year based on 250 working days. With a macro you can cut that time to under 50 hours.

The SolidWorks API offers a very broad function library. Almost every operation can be programmed, from opening, editing and saving Part, Assembly and Drawing files to adding custom properties, creating a bill of materials (BOM) and exporting to PDF.

SolidWorks Macro Automation Fundamentals with VBA

You access the SolidWorks VBA editor via Tools > Macro > New. A basic SolidWorks macro starts with the following structure: the lines Dim swApp As SldWorks.SldWorks and Set swApp = Application.SldWorks establish access to the SolidWorks application.

To access the active document, the lines Dim swModel As ModelDoc2 and Set swModel = swApp.ActiveDoc are used. These two lines form the foundation of almost every macro. You can then access geometry, features and configurations through swModel.

For error trapping, it is important to add error handling with an On Error GoTo line. If no file is open or no selection has been made while the macro is running, the program must not crash; it should show the user a meaningful message.

Using the SolidWorks API

The SolidWorks API has four main object models. The SldWorks object represents the application. ModelDoc2 represents the open document. PartDoc, AssemblyDoc and DrawingDoc provide functions specific to each document type. The Feature, Body and Face objects give access at the geometry level.

The SolidWorks API Help file is your most important reference source. The API Help that ships with the SolidWorks installation documents all objects, methods and properties with detailed explanations and code examples.

All of the Sheet Metal functions we describe in our SolidWorks sheet metal design guide are also accessible through the API. This lets you automate sheet metal operations with macros.

Sheet Metal Macro Examples

One of the most frequently used SolidWorks macro examples is the batch DXF export macro. This macro automatically saves the flat patterns of all sheet metal parts in an Assembly file in DXF format. A separate DXF file is created for each part, and the file name is taken from the part number.

The second popular example is the automatic flat pattern macro. It opens the Flat Pattern feature of the active sheet metal part, reads the flat pattern dimensions and writes them to the Custom Properties. This information is used in the BOM list and the cutting plan.

The third example is the automatic BOM creation macro. It reads all parts from the Assembly file, collects material, thickness, quantity and dimension data, and exports it to an Excel file. This macro saves a great deal of time, especially when sending orders to a subcontract manufacturer.

Advanced SolidWorks Macro Tips and Performance

To improve macro performance, use the lines swModel.SetAddToPart = False and swApp.CommandInProgress = True. These settings disable screen refresh and command history recording, making the macro run much faster.

For configuration-based operations you can switch between configurations with the swModel.ShowConfiguration2 method. By exporting a separate DXF or PDF for each configuration, you can automate multi-variant management.

By compiling your macros as an Add-In instead of .swp, you can add a button to the SolidWorks toolbar. This gives one-click access to the macro. In our technical drawing and BOM list article we also touched on documentation automation.

Calculating Time Savings with SolidWorks Macros

In a typical sheet metal design office, the time savings achieved through macro automation are as follows. Batch DXF export drops from 45 minutes done manually to 2 minutes with a macro. Preparing the BOM list drops from 30 minutes done manually to 1 minute with a macro.

Applying a technical drawing template drops from 20 minutes done manually to 30 seconds with a macro. Updating the revision number drops from 15 minutes done manually to 10 seconds with a macro. The total daily saving averages around 2-3 hours.

On a yearly basis this saving amounts to 500-750 hours. Taking an engineer’s hourly cost as 200 TL, this delivers a yearly cost advantage of 100.000-150.000 TL. The macro development investment usually pays for itself within 1-2 months.

Conclusion: Burak Engineering SolidWorks Macro Development

SolidWorks macro programming is one of the most effective ways to increase engineering productivity. You can start with VBA to build basic automations and develop more complex solutions over time. With the broad function library offered by the SolidWorks API, you can automate anything within the limits of your imagination.

At Burak Engineering we offer automation development, VBA training and custom automation solutions. We speed up your design process by developing macros tailored to your business.

Reach us through our contact page to get a free preliminary assessment for SolidWorks macro development and automation consultancy.

SolidWorks API architecture: how a macro reaches the model

Every reliable SolidWorks macro rests on the same object chain. Code written without understanding that chain breaks at the first version upgrade or the first time it meets a different document type. Getting the chain right is what keeps an automation alive for a decade.

The chain starts at the application object and descends toward individual features: the application layer represents the session, the document layer the open file, and the feature manager every node in the tree. The selection manager holds whatever the user or the code has highlighted, while the document extension is where the modern methods live.

  • Application layer — opens the session, manages document open and close, and controls user preferences.
  • Document layer — exposes separate interfaces for parts, assemblies and drawings, with shared operations on a common document interface.
  • Feature manager — walks the design tree, adds and removes features, and reorders them.
  • Selection manager — reports the type, count and mark of the current selection and must be cleared before every operation.
  • Document extension — hosts selection by persistent identifier, command execution and advanced save methods.

Early binding or late binding?

Early binding references the type library, which buys you code completion and compile-time checking. The price is a hard dependency on the referenced release. Late binding resolves objects at run time, so the code travels between versions freely, but typing mistakes only surface while it runs.

In practice we use a hybrid: develop quickly with early binding, then convert the critical calls to late binding before deployment so the tool survives upgrades.

CriterionVBA macro.NET add-in
Development speedVery high, editor built inModerate, separate build step
DeploymentCopy a fileInstaller and registration
UI integrationLimited, button assignmentTabs, menus and task panes
Source controlDifficult, binary formatEasy, plain-text source
Maintenance costLow for small toolsLow for large projects
Best suited toQuick single-office winsEnterprise, multi-user workflows

What a production-grade SolidWorks macro looks like

The difference between code that works and code you can trust is what happens when something goes wrong. An automation that quietly produces the wrong result across hundreds of files overnight costs far more than one that simply refuses to run.

Input validation and safe selection

The first job of the code is to confirm that a document is open, that it is of the expected type, and that the configuration it needs actually exists. Before anything is selected the current selection is cleared, and the boolean returned by the selection call is always checked.

Nothing that depends on screen coordinates, fixed indices or whatever the user happened to click reaches production. Objects are resolved through their persistent identifiers.

The unit trap

The API always works in metres and radians while the interface shows millimetres and degrees. Code that mixes the two produces errors of a thousandfold. Collecting the conversion into a single helper function removes that entire class of defect.

Rebuild, undo and warning control

After a batch of changes a forced rebuild is issued and its result inspected. Wrapping the whole operation in a single undo group lets the user step back in one action if the outcome is not what they expected.

Dialogs are suppressed for silent operation, but the preferences must be restored when the macro finishes and also when it fails. Otherwise the user carries on working in a session where warnings are switched off.

A rule from the shop floor

Every SolidWorks macro run should leave one line in a log: file name, operation, duration, result and error message. That single habit turns troubleshooting from hours into minutes.

Batch processing patterns: hundreds of files overnight

Automating a single operation is easy. The real gain comes from applying that operation safely to every file in a folder. Three things must be settled before you write the loop: traversal, opening and recovery.

  1. Traversal — the folder tree is walked recursively, filtered by extension and name pattern, and the work list is built in memory first.
  2. Ordering — parts first, then sub-assemblies, then the top-level assembly. Working in the reverse order invites reference errors.
  3. Silent open — the document is opened with warning and error flags captured; read-only mode noticeably shortens load time on large assemblies.
  4. Operation — the actual work happens here and every step has its return value checked.
  5. Close — documents are closed without saving; only files that genuinely changed are written back.
  6. Recovery — if one file fails the loop does not stop. The error is logged and the next file is processed.

With this pattern a thousand-part archive can have its flat patterns and cutting files regenerated in a single out-of-hours session. The only thing to check in the morning is the error log.

Missing references and path problems

Unresolved references while opening assemblies are the most common failure point in batch work. Defining the search folders at the start of the macro and restoring them at the end eliminates most of these errors.

Sheet metal and drawing automation

The fastest payback in automation comes from repetitive output. For sheet metal parts that means flat patterns and cutting files; for drawings it means view placement and the bill of materials.

Flat pattern and cutting file quality

Whether a cutting file runs cleanly on the machine depends less on the geometry than on the layer structure. Outer profile, inner profiles, bend lines and etch geometry belong on separate layers, and those layers must map to the technology table on the machine side.

  • The outer profile must be a single closed curve with no duplicate edges.
  • Separating inner profiles by hole diameter allows a different cutting speed for small holes.
  • Bend lines are kept on their own layer together with direction and angle information.
  • The flat pattern is taken from the configuration calculated with the bend table and K-factor actually used in production.
  • File names are generated in code so that part number, revision and thickness are always present.

Drawing generation

Drawing automation begins with a template. The code places the views, chooses a scale to suit the sheet size, links the bill of materials and updates the revision table. Because output naming passes through a single rule function, the archive stays consistent.

This workflow delivers most where a SolidWorks macro and a parametric model are built together: a dimension changes, the model rebuilds, and drawing and cutting file refresh themselves.

Performance and reliability settings

Run time usually comes from opening and rebuilding models rather than from the code itself. A handful of settings shorten the total considerably.

  • Lightweight components and large assembly mode cut load times on big structures.
  • Loading only the required configuration reduces memory consumption.
  • Deferring rebuilds between intermediate steps pays off whenever many dimensions change at once.
  • Turning off screen updates gives a noticeable speed-up in long loops.
  • Recording elapsed time per file makes bottleneck models easy to identify.

Security, versioning and deployment

An automation is not a file you write once and forget; it is a software asset under maintenance. As soon as more than one person in the office uses the same tools, deployment and version discipline become mandatory.

  • Security level — in a corporate environment macros should run only from defined trusted locations.
  • Single source — tools live in one network folder and desktop copies are not permitted.
  • Version stamp — every tool writes its own version number to the log, so a bug report always identifies the build that ran.
  • Source control — code is kept as plain text in a repository and changes are reviewed before merging.
  • Upgrade testing — before moving to a new release the tools are exercised against a representative set of files.

When should you move to an add-in?

As the number of tools grows the same helper routines start to repeat across files. That is the moment to move the shared library into a single add-in, which lowers maintenance cost and gives users a coherent interface. Past roughly five tools the migration usually pays for itself.

Common failure modes and their fixes

SymptomLikely causeFix
The macro silently does nothing on some filesA selection call fails but its return value is never checkedCheck the boolean after every selection and log the failure
Dimensions come out a thousand times too big or smallA millimetre value is passed straight to an API methodRoute every unit conversion through one helper function
Batch processing stops at the first errorNo error handling inside the loopProcess each file in its own error block so the loop continues
Parts cannot be found when an assembly opensSearch folders are not definedAdd search paths at the start of the macro and restore them at the end
Warnings stay switched off for the userPreferences are not restored when the macro failsMove the restore step into the exit path of the error block
Code breaks after a version upgradeEarly binding ties the tool to an old type libraryConvert critical calls to late binding and run an upgrade test
The same tool behaves differently for different usersStale copies exist on desktopsEnforce one central location and a version stamp

Go-live checklist

  • Are the active document and its type validated?
  • Is the selection cleared before each operation and the return value checked?
  • Does every unit conversion pass through a single point?
  • Is the whole operation wrapped in one undo group?
  • Are warning preferences restored on failure as well as on success?
  • Does each run produce a log line?
  • Is the tool in a central location and version stamped?
  • Was it tested against a reference file set before the version change?

An automation that passes these eight items can be moved into daily use with confidence. Tools that do not pass should stay with a single pilot user until they do.

solidworks macro technical application image
Technical view from a solidworks macro application.
solidworks macro process detail image
Detail inspection during the solidworks macro process.

FAQ

Frequently Asked Questions

What is solidworks macro automation?

SolidWorks macro automation with VBA: record and edit macros, drive parametric models, automate drawings, DXF export and repetitive design tasks.

What Is a SolidWorks Macro and What Does It Do?

This tool consists of automation scripts written using the SolidWorks API. They are written in VBA (Visual Basic for Applications) and saved with the .swp extension. Macros can be recorded via Tools > Macro > Record on the menu bar, or written from scratch.

SolidWorks Macro Automation Fundamentals with VBA: what should you know?

You access the SolidWorks VBA editor via Tools > Macro > New. A basic SolidWorks macro starts with the following structure: the lines Dim swApp As SldWorks.SldWorks and Set swApp = Application.SldWorks establish access to the SolidWorks application.

Using the SolidWorks API: what should you know?

The SolidWorks API has four main object models. The SldWorks object represents the application. ModelDoc2 represents the open document. PartDoc, AssemblyDoc and DrawingDoc provide functions specific to each document type. The Feature, Body and Face objects give access at the geometry level.

How can I work with Burak Engineering on solidworks macro automation?

Share your drawings and goals; we review your solidworks macro automation requirements and propose a suitable working model. Get in touch through the contact page.