1Today's goals
- Record, edit and run a macro
- Read the API object chain: SldWorks → ModelDoc2 → Extension
- Loop through a folder and export files
- Write custom properties from code
- Run macros safely
2What the API is
Everything you click in SolidWorks is also available to a program through the SolidWorks API. A macro is a small program inside SolidWorks: VBA (.swp, the most common), or VSTA in VB.NET/C#. Bigger tools become add-ins written in C# or VB.NET.
| Object | What it is | Typical calls |
|---|---|---|
SldWorks | The application | ActiveDoc, OpenDoc6, CloseDoc, GetExportFileData |
ModelDoc2 | Any open document | GetTitle, GetPathName, ForceRebuild3, Save3 |
ModelDocExtension | More document functions | SaveAs (export), CustomPropertyManager, SelectByID2 |
PartDoc / AssemblyDoc / DrawingDoc | Type-specific functions | bodies, components, sheets and views |
FeatureManager | Creates features | extrudes, fillets, holes |
Tools ▸ Macro ▸ Record writes code while you click — a great way to discover call names, though recorded code is long and full of exact pick points. Tools ▸ Macro ▸ New / Edit / Run. The API Help (Help ▸ API Help) lists every call with examples — it is the final authority.
3Do it in SolidWorks
- Tools ▸ Macro ▸ Record. Change a dimension, rebuild, stop and save as rec1.swp. Open it with Edit and find your dimension value in the code.
- Tools ▸ Macro ▸ New → batch_step.swp. Paste the "Parts → STEP" macro from the lab and change the folder.
- Copy five parts into a test folder. In the VBA editor open View ▸ Immediate Window, then run with F5. Read the log lines.
- Set STEP options first: System Options ▸ Export ▸ STEP → AP214. The macro uses whatever is set there.
- Try the PDF macro on a folder of multi-sheet drawings and confirm every sheet is in the PDF.
- Try the custom property macro on an open part; check File ▸ Properties.
- Assign a macro to a toolbar button: Tools ▸ Customize ▸ Commands ▸ Macro → New Macro Button.
4Lab: macro generator
Choose a job, set the folder, and click each line of the generated code to see what it does. The code uses the standard SolidWorks API calls and the constants from the SolidWorks type libraries that new macros reference by default.
5Pro tips and common mistakes
- Object variable not set — something returned
Nothing(no document open, wrong document type, file failed to open). Check before using it. - Use
Debug.Printand the Immediate window rather than manyMsgBoxlines. - Keep macros in a shared, version-controlled folder and put the standard header block at the top so you know what each one does.
- Recorded selections (
SelectByID2with coordinates) break on other models — select by name instead.
6Practice
Write a macro that opens every drawing in a folder, exports a PDF and a DXF of sheet 1, and writes one line per file (name, OK/FAILED) into a text file using VBA Open … For Append.
7Quick quiz
Five questions. Click an answer — you get the explanation straight away.