Macros for SOLIDWORKS: the absolute basics

This post is about how to create, edit and debug SOLIDWORKS macros when you are completely new to building software.

We’ll record a simple macro, explain the code and clean it up. Then we explain how you can debug your own macros.

You don’t need to be a software engineer by profession to be able to create macros, but a basic understanding of programming will help. I myself am a mechanical engineer by trade. I only started coding professionally when I started CAD Booster in 2017.

In this post, you’ll find

  1. What is a macro?
  2. What is an add-in?
  3. How to record a SOLIDWORKS macro
  4. VBA editor: what is the immediate window?
  5. Explaining the recorded code
  6. Improving the recorded code
  7. Checking the model type to prevent errors
  8. How to debug VBA SOLIDWORKS macros
  9. How to pick a language
  10. Sources and courses

1. What is a macro?

SOLIDWORKS has two flavors for automation: macros and add-ins. Macros are the most accessible, so we’ll start with those.

We’ll be using VBA or Visual Basic for Applications. VBA is an old Microsft programming language for creating macros for applications like Excel.

A VBA macro is a single .SWP file that can sit anywhere on your computer. You can run the macro by browsing for it or by adding a shortcut button to your command manager in SOLIDWORKS..

You can even record and play back macros, although not all actions can be recorded.

The advantages of macros

  1. Relatively easy to get started with.
  2. SOLIDWORKS contains an editor to create and edit macros.
  3. Can be created in VBA (Visual Basic for Applications), VB (Visual Basic, formerly VB.net) and C#.
  4. You can quickly create a new macro. By now, I can build a simple macro in two minutes.
  5. If you are familiar with macros in Excel, you can reuse much of that knowledge.
  6. You can run them in a batch tool like #Task, although I’m not a big fan of that product.

The disadvantages of macros

  1. The forms look ugly and gray unless you put in some real work.
  2. You cannot create task panes (those tabs on the right).
  3. You cannot do proper version control because the SWP file is not a text file. Version control software like Git can therefore not see what you have changed, only that the file has changed.
  4. It’s hard to roll out updates because:
    1. Files can become locked when you access them with multiple people. I’ve heard people say they had to wait till everyone went home to update the macro file.
    2. When everyone has their own file, you are never sure everyone is using the same version.

2. What is an add-in?

If you want to make a professional product that integrates with SOLIDWORKS, you need to build an add-in.

With add-ins, you can create Property Manager Pages (PMPs, those menus on the left, that let you edit Extrude properties, for example) and task panes (the menu tabs on the right).

Add-ins are usually installed on your computer with a Windows installer. After that, your new add-in appears in the list of available add-ins:

enable solidworks routing add-in

Add-ins can be built by SOLIDWORKS (like SOLIDWORKS Routing) or by third parties like CAD Booster. We develop and sell the products Drew (for drawing automation) and Lightning (the fast fastener filter) and we also build custom add-ins for our customers.

The advantages of add-ins

  1. Completely integrated within SOLIDWORKS.
  2. You can create them in any programming language that supports COM. Frequently used languages are C#, C++ and Python.
  3. Allows you to create task panes and property manager pages.
  4. You can create your own user interface (with WPF, for example) in the task pane. There’s no need to use the ugly gray user interfaces from 20 years ago from Windows Forms.
  5. You can do proper version control (with Git, for example) because the source code is stored in multiple text files.
  6. Users can easily install add-ins and their updates with an installer.

The disadvantages of add-ins

  1. There is a steep learning curve if you have never built software before, or if you have never built software for SOLIDWORKS before.
  2. You need external tools like Visual Studio to develop the software.
  3. You need to compile your code and create an installer.

Overall, we love add-ins and we rarely build macros for our customers.

3. How to record a SOLIDWORKS macro

The first step in learning how to create macros is by recording your own actions using the macro recorder.

Prepare your model file, hit record and only perform the actions that you want to record. Hit stop to save the file.

record solidworks macros

This great video by GoEngineer shows you how to record your actions and let SOLIDWORKS convert them into a macro. You can then create a button in your toolbar to run the macro whenever you need it again.

SOLIDWORKS does not record all of your actions, though. This is confusing and annoying for people that are just getting started. So don’t be surprised if your action does not show up in the macro. Just be disappointed 😉

The macro recorder does record most actions that create geometry or features. It does not record many of the clicks in the user interface.

4. VBA editor: what is the immediate window?

I have recreated the actions in the video above and saved the result. Clicking the rightmost button in the macro toolbar opens up the Microsoft Visual Basic for Applications editor. In my case, it looks like this.

VBA editor window solidworks

The window has five sections:

  1. Upper left: Project Explorer.
    • Here you can find the modules, user forms, class modules and SOLIDWORKS objects in your macro. Right-click to add any one of those things.
  2. Lower left: Properties window.
    • When you select an element in a UserForm, this section shows the properties of that element.
  3. The big one in the center: your main window for the code.
  4. Lower center: Immediate window.
    • You can write text to this window for easy debugging. The text will stay there until you manually select and delete it.
  5. Lower right: Watches.
    • You can right-click a variable and add a watch to it. When you step through the macro with a few lines at a time, you can follow how the contents of this variable change with each step.

One window that is not visible here is the Locals window. The Locals window shows you a list of the variables in your code and their current values.

If you don’t see a certain window, click View at the top to enable the missing window.

5. Explaining the recorded code

I added numbers in red to the previous image to explain the code.

I’ve written down everything that is happening in this short macro, everything that does not make sense and everything that I think you should know.

recorded macro result

  1. A line that starts with a single quote ( ‘ ) is a comment
    • Commented code will not be executed.
    • It is good practice to start your macro with a few lines on the who, why and how.
    • You can comment out part of a line. Anything on a line after the apostrophe is ignored.
  2. The variable called swApp is created, or defined.
    • It starts with Dim, a standard word to create a dimension new variable, then its name, as and its type.
    • This variable is used in every SOLIDWORKS macro and most people call it swApp to be able to read each others’ code easily.
    • It starts with a prefix (sw) to help you understand its type (a SOLIDWORKS object). This way of working is called Hungarian notation and it has gone out of style by now. Notice how it is used for longstatus (type = long) and longwarnings as well.
    • The rest of the name is a user-friendly name. In this case, app is short for application, the SOLIDWORKS application itself.
    • The variable type is object, which means it can basically contain anything. It is better to pick a more narrow variable type so cannot put incorrect data into the variable.
    • If your object has no value yet, it is nothing. When you then try to do anything with it, you get the cryptic error message Object variable or with block variable not set.
    • If you define a variable outside of a sub or function, you can access it everywhere in your macro. It’s a global variable. This sounds great, but you should avoid using these as much as possible.
  3. Other variables are defined
    • As you can, see you can define multiple variables on one line
    • If you don’t specify a type (“Dim swApp”), the variable will be a variant.
    • Variants are strange types that can contain any type of data, but you need to convert them to specific types if you want to do some real work with them
    • Variants are required for for each loops.
  4. The subprocedure called main is created.
    • Everything until the End Sub at line 19 is a part of the main subprocedure.
    • The brackets after main can contain variables, called arguments or parameters, that this subprocedure needs to function. In this case, we don’t need any.
    • Main is the subprocedure that gets called by default when no subprocedure is specified.
    • If there is no subprocedure without arguments called main, any subprocedure may be called. That is not what you want, so keep Main as the starting point.
  5. The swApp variable is set to the current SOLIDWORKS application so that our macro can talk to SOLIDWORKS.
    • The underscore _ is there for no reason at all. It allows you to create long lines of code that are on multiple lines. You can safely remove the underscore and the enter so the line becomes set swApp = Application.SldWorks
    • If you are working with an object, you need to start the line with set, followed by the variable name, an equals sign and its new value.
    • If you are working with a value type like a string, integer (a whole number) or a double (a double-precision decimal number), don’t use the word set.
  6. The Part variable is set to the document that is currently open
    • Part is a really poor variable name here, because the active model may be a part, drawing, assembly or nothing.
    • Its actual type is ModelDoc2.
    • Notice that we get the part object from the swApp object. Objects have properties and methods. The active model is a property of the SldWorks object.

recorded macro result

(I repeated the image to make the post more readable)

  1. Because the variable Part is assigned the active document, you can now call special SOLIDWORKS functions (also named methods).
    • Add a dot after a variable name to see all available functions. If you don’t see any options appear, your object is probably just that, an object. Use a more specific type like SldWorks.SldWorks or ModelDoc2 to see more options.
    • Right here we use the method InsertSketch to start a sketch on a pre-selected surface.
    • If you call a method that needs parameters, and you want to store the return value, you need parentheses around the arguments. See line 15.
    • If you do not store the return value of a method or the method has no parameters, you need no parentheses. VBA allows both, which is confusing for beginners and annoying for experts.
  2. ClearSelection2 is the second and latest version of the ClearSelection method.
    • For some reason, SOLIDWORKS needed a newer version of this method. They never remove the old version so they don’t break older macros. The old method is now called Obsolete.
    • If anything was selected before the macro was started, it is deselected with this method call.
  3. A new sketch segment variable is defined
    • Because this variable is defined within a subprocedure, it is called a local variable, which means that it can only be used within this subprocedure.
    • The variables declared at the top at 2 and 3 can be used from anywhere and are called global variables.
  4. A circle is drawn by the coordinates of the center point and one other point on the circle.
    1. This line actually chains multiple objects.
    2. It uses the Part object (the active model), then its SketchManager object (an object that lets you create and edit sketches) and calls the CreateCircle method.
  5. The selection is cleared again
  6. InsertSketch is called again, this time to close the sketch
  7. The sketch is opened again.
  8. The selection is cleared again, this all seems pretty useless.
  9. The sketch is selected
  10. A new variable that can hold a feature is defined
  11. A new feature is created using the selected sketch and a whole lot of options.
    • Don’t even bother trying to remember all options. The help page will tell you what those options are. I visit the API Help every single day.
  12. EnableContourSelection can be used to select the contour of the sketch for the cut extrude.
    • We don’t need that option anymore, so it can be disabled. Notice it wasn’t enabled in this code, so it is probably enabled by default.
  13. The main subprocedure is closed.
    1. You can have multiple subprocedures and functions. I fact, it is a good practice to try to limit each function and procedure to about ten lines of code.
    2. Officially, a subprocedure returns no value and a function does. You can, however, create a function that returns no value
    3. To create a function that returns a value, type as and a type after the function’s brackets. Example: Function ReturnModel() as ModelDoc2.
    4. To set the value that you want to return, use the name of the function. If you return an object, start with set. Example: set ReturnModel = swModel.

6. Improving the recorded code

The output from the macro recorder is far from great.

It does not even use all variables and some lines are in there way too many times. Time to clean it up. This is what it can look like afterwards.

solidworks macros - cleaned up recording

As you can see I have:

  • Moved the variable declarations to the top of the program for clarity (2020 update: don’t create a long list of all variables at the top of your program)
  • Chose more narrow variable types to prevent weird, unpredictable behavior.
  • Removed the underscore at the definition of swApp. The underscore is used to split a long line of code across multiple lines. That’s not the case here.
  • Removed all of the selection clearing
  • Removed two of the Insert Sketch lines that didn’t do anything.
  • Set the draft angles of the feature to zero instead of 1.7451558415E-02. Two of the ‘false’ statements were to disable a draft anyway.

The functionality hasn’t changed a bit though. It still creates a sketch and a cut-extrude on a previously selected face.

And now that I am refreshing this blog post in 2020, I would make even more changes:

  1. I would move the global variables into the subprocedure. No globals unless we really need them.
  2. I would remove longstatus and longwarnings because they are never used.
  3. I would remove boolstatus if we don’t need its value after calling SelectByID2. We then need to remove the brackets around the parameters.
  4. I would rename Part to swModel and make it of type ModelDoc2. The naming is the convention in SOLIDWORKS macro land. The Part type is too restrictive because the model can also be an assembly.
  5. I would renamed myFeature to swFeat, also a convention.
  6. I would declare my variables just before I need them. This makes it easier to find out their type and makes it easier to spot problems. List all of you variables at the top is and old C++ convention that we don’t need here.

7. Checking the model type to prevent errors

It is good practice to be ready for all possible situations.

Your code should not crash or give an error when the user does something unexpected. It is your fault that you did not expect that, so don’t blame the user.

So we’re adding some basic checks, which include, in this order:

Check if swModel is Nothing

After we get swApp, we can get the active model.

Getting swApp never goes wrong. But if not model is open, swModel will be nothing. In that case, we show a message box to the user. End stops execution of the macro entirely.

Check if the model is the correct type

If you only want to work with the ModelDoc2 object, you don’t need these checks. But when you want to call methods that are only available for part, assembly or drawing objects, you need to verify the active model type. To make sure the model is a part:

Other checks

For this particular macro, we should also check if the user selected a face beforehand. If not, you can give the user a message box with an error and stop the execution of the macro.

8. How to debug VBA SOLIDWORKS macros

There are a few options that you should know when you want to properly test en debug your bits of code:

Step by step

You can execute your code until a certain point by setting your cursor where it needs to pause and click Debug > Step into or press F8. The code runs until it reaches this point. From there you can run it line by line by pressing F8, this is a great way to debug your own code or to get to know another macro.

Pressing F5 calls the run command and runs the macro until the end or until you reach a breakpoint.

solidworks macro step though debug

Breakpoints

By left-clicking before a line, you can add Break Points. The execution of code stops at these points.

Now you can assert the values of variables by hovering over them or by checking those that you’ve assigned watches to.

Pressing the play button will make it hop until the next breakpoint, hitting stop will make it stop immediately.

Debug.Print [variable name]

This line adds the contents of one or multiple variables to the Immediate Window, as long as they contain text or numbers. You can combine multiple strings or values with an ampersand (&).

Example: Debug.Print “The value of boolstatus is ” & boolstatus

vba macro immediate window debug.print

Debug.Assert [variable name] [condition]

The line Debug.Assert x > 10 will assert whether x is indeed greater than 10 and it will pause the program if it isn’t.

Call stack

The last tool for debugging that I want to mention is the Call Stack option.

When the code execution is started and paused, you can press View > Call Stack or Ctrl + L to see how the current function has been called by other functions. This is a really powerful tool, although the VBA implementation isn’t that great.

9. How to pick a language

You can write macros in three Microsoft-based programming languages. The first one is Visual Basic for Applications (VBA), of which you have seen a lot above.

It is easiest to start with VBA because it is the most accessible option. The help website by SOLIDWORKS is also extensive and sorted by version.

VB (which used to be called VB.NET) and C# are the other two options. These are the more modern and more advanced options. They also allow you to create add-ins for SOLIDWORKS, this isn’t possible with VBA.

10. Sources and courses

Here are some useful sites when you want to get started with building macros for SOLIDWORKS:

Doing a Google search in the form of SOLIDWORKS API [your search term] will also do miracles. I do that a dozen times per day.

If you want some professional guidance in your endeavors, you can enroll in this course by SOLIDWORKS:

Your current Value Added Reseller (VAR) can help you with official SOLIDWORKS courses.

11. Or just let us build you a macro (or add-in)

I started CAD Booster four years ago to automate the boring bits of my engineering job. Since then, I have created add-ins like Drew and Lightning, plus a dozen others for our customers.

Because of all that experience, I know my way around the SOLIDWORKS API. So a macro that might take you days can sometimes take me only 30 minutes.

I will usually advise you to develop an add-in because they are more stable and can be maintained properly, but I also just finished a macro for a customer.

Check out the Contact page for our email address and phone number.

12. Final words

Are you excited to build a simple program that can take over some of your daily tasks? I’m pretty sure there are some great ideas out there.

Now let’s get those little robots to do our chores!

Mis geen enkele post. Krijg een gratis add-in.

Schrijf je in voor onze nieuwsbrief en je krijgt onze TimeSavers add-in cadeau.