← LibrarySolidWorks API Macro Fundamentals: Recording, Reading and WritingEngineering · ComputersLesson 2/10← PrevNext →
ArticlePublished 4 Aug 20269 min readBy Kevin JoginSolidWorks APIVBAmacrosCAD automation

Engineering / Computers / Part 1 of 9

Macro Fundamentals

The macro recorder is the cheapest way into the SOLIDWORKS API and the most misleading. It produces working code within a minute, and code that will break the first time anything moves. Understanding exactly what it records — and what it quietly leaves out — is what turns a recording into a program.

  • Part 1 · Foundations
  • Recorder anatomy
  • Guards & error codes
  • Recording → program

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

A recorded macro is a transcript of a session, not a description of an intention. It captures the actions you performed on the objects that happened to be there, identified in the way the application happened to identify them at that moment. That distinction explains almost every problem people have with recorded macros.

3Type libraries a macro normally references
1Application object, obtained before anything else
0Guards the recorder writes for you

01What the recorder actually captures

Recording is available from the macro commands on the Tools menu. Start it, perform an operation, stop it, and SOLIDWORKS writes a macro file. What lands in that file is narrower than most people expect.

Recorded reliably

Operations that change the document — creating and saving files, adding features, applying mates, setting properties, changing view orientation. These map onto API calls directly, and the recorder writes those calls.

Recorded, but brittle

Selections. The recorder writes the selection as a name and a screen-space coordinate captured at the instant you clicked. Both are specific to that document at that moment.

Not recorded at all

Navigation, zooming and panning, dialogue browsing, and most interactions that do not modify the model. Nothing appears in the file, which is often mistaken for the recorder having failed.

Never recorded

Your reasoning. Loops, conditions, validation and error handling do not exist in a recording because you did not perform them — you decided them.

The point of recording

Use the recorder as a discovery tool: it tells you which API call corresponds to a command you know how to perform manually. That is genuinely valuable and hard to obtain any other way. Treat the output as a research note, not as a deliverable.

02Anatomy of a recorded macro

Open a recording in the Visual Basic editor and the same skeleton appears every time. Learning to read it takes minutes and pays off permanently, because every published example shares it.

VBAthe boilerplate you will see every time
Dim swApp   As SldWorks.SldWorks   ' the application
Dim swModel As SldWorks.ModelDoc2  ' whichever document we are acting on

Sub main()
    Set swApp = Application.SldWorks   ' inside SOLIDWORKS this is already available
    Set swModel = swApp.ActiveDoc      ' may legitimately return Nothing
    ' ... recorded actions follow ...
End Sub

Three things are worth naming explicitly.

Application.SldWorks
A macro runs inside the SOLIDWORKS process, so the application object is handed to it. An external program has to go and find a session instead — that is the subject of Part 2, and it is the main structural difference between the two.
ActiveDoc
Returns the document in the active window, or nothing at all when no document is open. The recorder never checks which. Your version must.
Declared types
Declaring the specific type rather than a generic object gives you editor completion and catches misspelled members before you run anything. It requires the right references to be set, covered below.

03Setting references

References are the links between your macro and the type libraries that describe the API. Without them, the specific type names will not resolve.

In the Visual Basic editor the reference list is reached from the Tools menu. Three libraries cover almost everything in this series:

SOLIDWORKS type library
The main object model — the application, documents, features, components, selections and managers.
SOLIDWORKS constant type library
Every enumeration. Without this, you cannot refer to option and type values by name, and your code fills with unexplained integers.
SOLIDWORKS exposed type libraries for add-ins
The published interfaces you implement rather than call — notably the PropertyManager page handler and the add-in contract. Needed from Part 5 onward.
Version drift

References point at the type libraries of a specific installed release. A macro carried to a machine running a different release may need its references reset, and a reference shown as missing is the usual symptom. This is a strong argument for keeping shared automation in a properly deployed add-in rather than in circulated macro files.

04From recording to a program you can trust

Converting a recording into something dependable is a repeatable transformation. It is worth doing deliberately rather than by instinct.

Step 1Add guardsConfirm a document exists and is the type you expect before touching it.
Step 2Replace picked selectionsSwap recorded coordinates for a query — find the entity by name, by traversal, or by asking the user through the selection manager.
Step 3Generalise the constantsHard-coded paths, file names and configuration names become inputs.
Step 4Capture errorsRead the error and warning outputs the recorder discards, and act on them.
Step 5Restore statePut the selection, configuration and open documents back the way you found them.

Step 2 is the one that matters most. A recorded selection is expressed as an entity name together with a coordinate that was under the cursor at the time. Neither survives a rebuild, a different configuration, or a different part. Any macro that will run on more than the document it was recorded against must select by interrogation rather than by replay.

Practical test

Before trusting a converted macro, run it against a document it was not recorded on, then against one with no document open, then twice in a row. Those three cases catch the overwhelming majority of defects.

05Writing one from scratch

A macro written deliberately is shorter than the recording it replaces, because it does one clear thing and says so.

VBAminimum viable macro with guards
Option Explicit

Dim swApp   As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2

Sub main()

    Set swApp = Application.SldWorks

    Set swModel = swApp.ActiveDoc
    If swModel Is Nothing Then
        MsgBox "Open a document first.", vbExclamation
        Exit Sub
    End If

    If swModel.GetType <> swDocumentTypes_e.swDocDRAWING Then
        MsgBox "This tool expects a drawing.", vbExclamation
        Exit Sub
    End If

    MsgBox "Working on: " & swModel.GetTitle

End Sub

Option Explicit at the top forces every variable to be declared, which turns a whole class of silent typing errors into compile errors. It costs nothing and should be standard practice.

The document type check uses GetType, which returns a member of swDocumentTypes_e. The values distinguish no document, part, assembly and drawing. Compare against the named member, never the integer.

Why two guards, not one

The two failures are different and deserve different messages. "Nothing is open" is a user sequencing problem; "the wrong kind of document is open" is a scope problem. A single generic error tells the user neither, and generates a support request.

06Creating and saving documents

Two calls cover most document lifecycle work, and both have details worth knowing before you rely on them.

Creating from a template

A new document is created from a template path, together with a paper size and sheet dimensions. For parts and assemblies the size arguments are ignored; for drawings they determine the sheet. The call returns the new document, so capture it rather than reaching for the active document afterwards — that is a race you can avoid entirely.

VBAcreate, then verify
Dim swPart As SldWorks.ModelDoc2
Set swPart = swApp.NewDocument(templatePath, 0, 0#, 0#)

If swPart Is Nothing Then
    MsgBox "Template not found or not readable: " & templatePath, vbCritical
    Exit Sub
End If

Template paths differ between installations and between users. Reading the configured template location from user preferences, rather than embedding an absolute path, is what makes a macro survive being given to somebody else.

Saving with intent

Saving takes a destination, a version argument, an options argument and outputs for errors and warnings. Two habits matter:

  • Use the silent option deliberately. It suppresses dialogues that would otherwise stop an unattended run — which is exactly what you want in a batch tool and exactly what you do not want while debugging, because the dialogue was telling you something.
  • Read both outputs. The error output reports failure; the warning output reports a save that happened but not the way you assumed. Ignoring warnings is how a batch job reports complete success and produces files nobody can open.
File extension drives format

The output format is inferred from the extension you supply in the destination path. The same save call writes a native part, a DXF, a STEP file or a PDF depending on the extension alone. Format-specific behaviour — which entities a DXF export includes, for example — comes from the corresponding export options in system settings, not from the call. Set those once, verify the output visually, and record the settings alongside the tool.

07When a macro is the wrong tool

Macros are excellent for a narrow band of work. Recognising the edge of that band early saves rewriting later.

Symptoms that a macro has outgrown its format
SymptomWhat it indicatesMove to
Needs a real user interfaceDialogue boxes no longer express the choicesA PropertyManager page (Part 5) or a .NET client (Part 2)
Runs over many files unattendedWork happens outside a modelling sessionA stand-alone .NET client (Part 2)
Used daily by a teamDistribution and versioning now dominateAn add-in (Part 9)
Needs data from another systemDatabases, spreadsheets, web servicesA .NET client or add-in with proper libraries
Copies have divergedGovernance failure, not a technical oneA single controlled deployment

None of this argues against starting with a macro. Prototyping the logic where iteration is fastest, then repackaging once the behaviour is settled, is a sound sequence — provided the repackaging is planned rather than indefinitely deferred.

08Quick reference

Application.SldWorks
The application object, available directly inside a macro.
ISldWorks::ActiveDoc
The document in the active window, or nothing. Always test it.
IModelDoc2::GetType
Returns a swDocumentTypes_e member — none, part, assembly or drawing.
IModelDoc2::GetTitle
Window title of the document; useful in messages and logs.
IModelDoc2::GetPathName
Full path, or an empty string for a document never saved.
ISldWorks::NewDocument
Creates from a template and returns the new document.
IModelDocExtension::SaveAs3
Current save call; format follows the file extension. Older SaveAs2 remains in most releases.
swSaveAsOptions_e
Bit flags for the save behaviour, including silent operation and copy mode.
Option Explicit
Not API, but the single cheapest defect-prevention measure available in VBA.

Continue learning

SolidWorks API Programming and Automation: Series OverviewArticle · ComputersNEXT LESSON →Connecting 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