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.
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.
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.
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 SubThree things are worth naming explicitly.
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:
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 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.
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.
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 SubOption 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.
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.
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 IfTemplate 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.
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.
| Symptom | What it indicates | Move to |
|---|---|---|
| Needs a real user interface | Dialogue boxes no longer express the choices | A PropertyManager page (Part 5) or a .NET client (Part 2) |
| Runs over many files unattended | Work happens outside a modelling session | A stand-alone .NET client (Part 2) |
| Used daily by a team | Distribution and versioning now dominate | An add-in (Part 9) |
| Needs data from another system | Databases, spreadsheets, web services | A .NET client or add-in with proper libraries |
| Copies have diverged | Governance failure, not a technical one | A 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.
