Modular code is the key to professional automation. By breaking your SOLIDWORKS macros into smaller, reusable pieces, you make your scripts easier to debug, update, and share across different projects. This lesson focuses on Subroutines (Subs) and Functions the two primary containers for your logic.
Key Takeaways:
- Subroutines (Subs): Use these to execute a series of actions (e.g. modifying a CAD property). They perform tasks but do not return a value.
- Functions: Similar to Subs, but they return a specific value (e.g., calculating the sum of two numbers or checking if a file exists).
- Parameters & Arguments: Make your code dynamic by passing data into your modules. You can use single or multiple parameters of any data type.
- Passing by Value vs. Reference:
ByVal: Passes a copy of the data. The original variable remains unchanged outside the module.
ByRef (Default): Passes a reference to the actual variable. Changes made inside the module will affect the original variable.
- Scope & Visibility: Use Public to make your modules accessible across the entire project or Private to restrict access to a single module.
- Early Exits: Use Exit Sub or Exit Function to stop execution immediately if a certain condition is met, skipping any remaining code in that block.