← LibrarySolidWorks API Programming and Automation: Series OverviewEngineering · ComputersLesson 1/10← PrevNext →
ArticlePublished 4 Aug 202610 min readBy Kevin JoginSolidWorks APICAD automationdesign automationVBA

Engineering / Computers / Series overview

SolidWorks API Programming & Automation

Every engineering office carries a tax it never records: the hours spent repeating work a computer could do exactly, every time, without fatigue. This nine-part reference sets out how the SOLIDWORKS API is structured, what it can reach, and how to build automation an engineering business can actually depend on.

  • 9-part series
  • Engineering · Computers
  • Object model · API help
  • Macro → add-in path

KL-ENG-COMP-1500 · KEVOS® Knowledge Library · Australian English

The SOLIDWORKS API is a COM interface that exposes almost everything the application can do to an external program. Anything a user can click, a program can generally call — create documents, drive dimensions, mate components, read and write custom properties, generate drawings, export files and extend the user interface itself.

What the API does not supply is engineering judgement. Automation multiplies whatever process it is pointed at, including a bad one. This series therefore treats API programming the way KEVOS® treats any capital process: define the duty first, choose the smallest mechanism that meets it, verify against real cases, and design for the day the release changes underneath you.

3Delivery vehicles — recorded macro, stand-alone client, add-in
1Root object; every other handle descends from it
SIThe API works in metres, radians and kilograms, always
9References in this series, each independently usable

01Where automation actually pays

Automation earns its keep where a task is frequent, rule-governed and error-prone by hand. Where any one of those three is missing, the payback usually is too.

Strong case

Repetitive output generation

Exporting every sheet of every drawing to DXF or PDF on a release; producing a standard drawing from a model; renaming and filing outputs to a naming convention. The rules are fixed and the volume is real.

Strong case

Data integrity across a set

Checking that every configuration of every part carries the custom properties your ERP or PDM expects, and correcting the ones that do not. Humans are poor at auditing hundreds of near-identical records; software is excellent at it.

Strong case

Enforcing a standard

Applying a company material list, a title-block rule or a mate convention consistently. The value is not the keystrokes saved — it is the variance removed.

Weak case

One-off geometry work

Modelling a bespoke part through the API is almost always slower to write than to model by hand, and far harder to change.

Weak case

Tasks that need judgement

If the rule cannot be written down without the word "usually", the process is not ready to be automated. Fix the process first.

Weak case

Unstable inputs

Automation against inconsistent legacy files spends its life in exception handling. Clean the data or scope the tool to the subset that is clean.

Engineering note

Estimate payback in rework avoided, not minutes saved. A DXF exporter that removes a whole class of "wrong revision issued to the laser cutter" events is worth more than its time saving suggests, because the cost it removes is a scrap-and-reissue cost, not a labour cost.

02The object model in one page

Nearly every API session follows the same shape: acquire the application object, ask it for a document, then ask the document for the specialised managers that do the real work. Learn this spine and the rest of the API becomes navigable.

ISldWorks The application itself. One per running session. Source of the active document, new documents, the command manager, user preferences and selection filters.
IModelDoc2 Any open document, whatever its type. Title, path, save state, rebuild, selection manager, configurations, summary information.
IPartDoc · IAssemblyDoc · IDrawingDoc Type-specific behaviour. Materials and bodies; mates and components; sheets and views. You obtain these by casting the same document handle.
IModelDocExtension The overflow interface. Newer capability is added here rather than to IModelDoc2 — selection by identifier, custom property managers, printing, mass properties, save operations.
ISelectionMgr What the user has picked, in what order, under which mark.
IConfigurationIComponent2IFeature The route into an assembly tree. Configuration first, because components and suppression states are configuration-specific.
ICustomPropertyManager Document-level or configuration-specific metadata — the bridge between CAD and every downstream business system.
Reading the names

The published reference documents interfaces with an I prefix (ISldWorks, IModelDoc2). In VBA and in .NET you will commonly declare the un-prefixed co-class name instead. They describe the same thing; the prefix is a documentation convention, not a different object.

03Three ways to deliver the same logic

The same fifty lines of API code can be shipped three different ways. The choice is a deployment decision, not a programming one, and it should be made before the first line is written.

Delivery vehicle selection — the same automation, three packages
CriterionRecorded / VBA macroStand-alone .NET clientAdd-in
Lives whereA .swp file on disk or a shared driveAn executable run from WindowsA registered library loaded by SOLIDWORKS at start-up
Starts howUser runs it from the macro menu or a toolbar buttonUser launches the program, which attaches to the sessionAppears as a menu, toolbar or task pane inside SOLIDWORKS
Best forPersonal shortcuts, prototypes, proving a sequence worksBatch work over many files, jobs run outside the modelling sessionAnything a whole team uses daily
User interfaceBasic dialogs onlyFull application windowsNative PropertyManager pages and command groups
Deployment effortCopy a fileCopy or install an executableRegistration required on each machine; version control matters
Maintenance riskHigh — copies diverge silentlyModerateLowest once a release process exists
Common failure

A macro that proves useful gets emailed around, edited locally, and within a year six incompatible versions are in circulation with no record of which produced which drawing. Decide early whether a tool is personal or organisational. If it is organisational, it needs a home, a version number and an owner — the same governance any other engineering artefact receives.

04The one skill worth learning first

Reading the API reference fluently is worth more than memorising any number of code samples. Four conventions unlock most of it.

1 · The trailing digit is a version, not a variant

Methods ending in a number — SaveAs3, Add3, Get6, SelectByID2, AddMate5 — are successive revisions of the same call. Each new version usually adds arguments and leaves the older one in place for compatibility. Always write against the highest-numbered variant your target release exposes, and record which release that is; it is the single most common reason code that worked last year fails to compile this year.

2 · Enumerations carry the meaning

Integers returned and accepted by the API are almost always members of a named enumeration — swDocumentTypes_e, swSaveAsOptions_e, swSelectType_e, swCustomInfoType_e. Reference the enumeration member by name rather than the literal value. The literal will be correct and unreadable; worse, it will still compile after the meaning changes.

3 · Option arguments are bit flags

Where the help lists several options for one argument, they are designed to be combined with a bitwise OR. A silent, copy-mode save is one argument holding two flags, not two calls.

4 · Errors arrive as output parameters

Many calls report success through arguments passed by reference rather than through the return value. A save operation that appears to succeed may have set a warning code you never read. Capture them, test them, and log them.

Practice

Before writing any new call, open its reference page and read three things in this order: the argument list, the remarks section, and the release in which it was introduced. The remarks section is where the behaviour that will surprise you is documented.

05The nine parts

Each part is a self-contained reference. Read in order for a learning path, or jump directly to the capability you need.

Part 1

Macro Fundamentals

What the recorder captures and what it silently omits; reading a recorded macro; writing one from scratch; document creation and saving; why recorded code is evidence rather than architecture.

Part 2

Connecting from Visual Studio

Interop references and the settings that trip everyone up; attaching to a running session; starting one; casting rules; COM object lifetime and release discipline.

Part 3

First Automation Tasks

The guard preamble every tool needs; batch export of drawing sheets; save options and error codes; reading document information; the system-units trap.

Part 4

Working with Selections

Selection as a contract with the user; marks and ordering; identifying picked entities; mating, materials and dimension values; programmatic selection and filters.

Part 5

PropertyManager Pages

Building native user interface inside SOLIDWORKS: the handler interface, control identifiers, page options, groups and controls, and the event lifecycle.

Part 6

Traversing Assemblies & Features

Recursive component traversal, the feature and sub-feature chain, filtering by type name, suppression states, and presenting a tree the user recognises.

Part 7

Custom Properties & Configurations

Document-level versus configuration-specific metadata, adding, updating, deleting and auditing properties, and why this is the highest-value automation in most businesses.

Part 8

Drawing Automation

Creating drawings from templates, standard view sets, walking sheets and views, counting and auditing, and printing with real control over ranges and devices.

Part 9

Add-ins & Deployment

The add-in contract, connect and disconnect, command groups and icons, COM registration and the registry entries involved, clean removal and rollout.

06A suggested learning path

  1. Record something trivial and read itCreate and save an empty part with the recorder running, then open the result. The goal is not the code — it is recognising the boilerplate you will see in every example from now on.
  2. Write one macro without the recorderOpen a document, check its type, report its title. Small, but it forces you to set references and handle the case where nothing is open.
  3. Move the same logic into a .NET projectThe code barely changes; the packaging, casting and error handling all do. This is where most of the friction lives, so meet it early on something you already understand.
  4. Automate one real, annoying task end to endBatch DXF export is the classic choice because the rules are unambiguous and the benefit is immediate.
  5. Add a proper user interfaceA PropertyManager page turns a personal script into something a colleague will use without being taught.
  6. Traverse, audit and reportWalk an assembly, collect what you find, and write a report. Auditing tools are low-risk, high-value, and they make the case for further automation with evidence.
  7. Package it as an add-inOnly once the logic is proven. Deployment is a separate discipline and deserves its own attention.

07Governance: making automation dependable

A macro that works on the author's machine is a demonstration. The difference between that and a tool the business can rely on is a short, unglamorous list.

Record the target release

State in the source header which SOLIDWORKS release the tool was written and tested against. When a call disappears or a suffix increments, this is the first thing anyone needs to know.

Fail loudly, never silently

Check every handle before use and every error output after use. An automation tool that quietly skips a file is worse than one that stops, because nobody finds out until the file is needed.

Keep a log

Write what was processed, what was skipped and why, with timestamps. This converts "the exporter is broken" into a diagnosable statement, and it is the evidence trail an audit will ask for.

Make it idempotent

Running the tool twice should produce the same result as running it once. Anything that appends, increments or renames on each pass will eventually be run twice.

Restore the user's state

If you clear a selection, change a configuration or open documents, put things back. Users who lose work to a tool stop using it, and tell others.

Test against ugly data

Validate on real legacy files, not the clean model you built for the purpose. The exceptions are the specification.

Change control

Treat an automation tool as a controlled engineering document. Version it, note what changed, and keep the superseded version retrievable. If a tool produced a manufacturing output, you must be able to say later which version produced it.

08Quick reference

Core interfaces — what to reach for, and how you obtain it
InterfaceResponsibilityTypically obtained from
ISldWorksThe application sessionThe programming environment, or a COM attach from an external program
IModelDoc2Any open documentActiveDoc, NewDocument, OpenDoc6
IModelDocExtensionNewer document capabilityThe Extension property of a document
IPartDocPart-specific behaviour, materials, bodiesCast from a document of part type
IAssemblyDocComponents and matesCast from a document of assembly type
IDrawingDocSheets and viewsCast from a document of drawing type
ISelectionMgrWhat is currently selectedThe SelectionManager property of a document
IConfigurationA named configuration and its tree rootGetActiveConfiguration
IComponent2One instance in an assembly treeGetRootComponent, then GetChildren
IFeatureOne entry in the feature treeFirstFeature, then GetNextFeature
ICustomPropertyManagerDocument or configuration metadataExtension.CustomPropertyManager
ICommandManagerMenus and toolbars added by an add-inGetCommandManager, using the add-in cookie

Continue learning

NEXT LESSON →SolidWorks API Macro Fundamentals: Recording, Reading and WritingArticle · ComputersConnecting to SolidWorks from Visual Studio in C# and VB.NETArticle · ComputersFirst SolidWorks Automation Tasks: Batch Export and Document InformationArticle · ComputersWorking with Selected Objects in the SolidWorks APIArticle · Computers