Home » Blog » SolidWorks API

Category Archive: SolidWorks API

Troubleshooting Error Messages in SolidWorks Macros – Part 6

There is nothing more frustrating than running into an error message in the process of writing or running a macro and not knowing what the issue is or how to even start fixing it. Hopefully this post will demystify the errors a bit and get you pointed in the right direction to solve the problem.

There are two main types of errors that you will run into when writing a SolidWorks macro: compile errors and runtime errors. Compile errors are usually caught as you’re writing the code. When you hit the “Enter” key to go to the next line, the VBA environment will pop up a message that looks something like this:

 

The offending line of code is highlighted in red. This type of error is a result of some incorrect programming syntax. The VBA language has many requirements about what has to be enclosed in parentheses, how loops (For loops, While loops, etc.) and If statements are structured, and much more. Breaking any of these rules will result in a compile error.

If you’re completely new to programming, picking up a book like VBA For Dummies will be a great help. If you’re already familiar with programming, doing some quick online searches to research the particular syntactical quirks of VBA should suffice.

As you spend more time with VBA in the SolidWorks API environment, the headache and mystery associated with these types of errors will greatly lessen.  Note that some types of compile errors pop up after the macro is run but before the code actually begins executing:

These are still syntactical errors, but they aren’t necessarily tied to the VBA language itself. These two examples both have to do with errors in the definition of the parameters of a method. The “Argument not optional” error indicates that one or more of that method’s parameters are missing. “Wrong number of arguments” usually means that there are more parameters than the method asks for. The number of parameters for each method is defined by SolidWorks in the API, and all parameters are required. The Help File is a good resource for figuring out what parameters are defined, what data type is needed, and how many there are.

Runtime errors are caught only when you try to run the macro. The code will execute part of the way through and stop at the error, popping up a message like this:

 

If you click the “Debug” button, the program will highlight the line of code that produced the error so you can target your efforts to fix it:

Here are a few common runtime errors and how to resolve them:

1.       Object or with block variable not set

This is most commonly due to trying to assign an object to a variable without using the “Set” keyword. Non-object variables are assigned without the “Set” keyword, as follows:

Dim i As Integer
i = 10

VBA requires that if a variable has been declared as an object of any kind, it must be assigned as follows:

Dim swVar As Object
Set swVar = Interface.Accessor

If this error pops up, check to make sure that you’ve used the “Set” keyword whenever assigning an object to a variable. Additionally, make sure that the variable has actually been set to an object before trying to use it.

2.       Object doesn’t support this property or method

 

This error means that you’ve tried to access a property or use a method that doesn’t exist in the API. Many times this simply means a typo – check your spelling and try again. Otherwise, you may be trying to use a method that actually belongs to another interface or incorrectly recalling the name of a method – for example, trying to use CreateCircleByDiameter (which doesn’t exist) instead of CreateCircleByRadius (which is a method belonging to the ISketchManager interface). Usually, a quick Help File search will allow you to resolve the problem.

3.       Type mismatch

You will see this error if you try to assign the wrong type of data to a variable that you’ve declared. For example, the following would produce this error:

Dim i As Integer
i = “Text string.”

The assignment of the variable to some text (String) doesn’t match the type of data (Integer) that the program was told to expect.  You will also see this error if you try to use the wrong data type for a particular parameter in a function.

For example, the CreateCircleByRadius function requires three parameters to define the X, Y, and Z locations of the center of the circle and a fourth to define the desired radius. All four parameters must be of the “Double” (an 8-byte floating point number) data type. If you try to give the function String data instead of Double data, you will see this error. Again, a quick Help File search for the method you’re trying to use will help clarify which data type is expected for each parameter.

If you get stuck on a particular error, don’t give up! Read the error message carefully, check the Help File, search the internet, call technical support, or use whatever other resources you have available to break the problem down.

If you’re interested in the SolidWorks API, make sure to check out the recorded webinar: “Introduction to the SolidWorks API”.

See the previous posts from this series:

Getting Started with the SolidWorks API – Part 1

SolidWorks API Building BlocksPart 2

SolidWorks API Building Blocks – Part 3

Commonly Used Interfaces in the SolidWorks APIPart 4

Using the SolidWorks API Help FilePart 5

Using the SolidWorks API Help File – Part 5

The Help File for the SolidWorks API (found under Help -> API Help) is a very convenient and useful resource when it comes to working your way through writing a macro. Not only does the Help File provide helpful information about specific components within the API, its organization also provides us with a lot of insight into the SolidWorks Object Model that we’ve been discussing.

There are two main ways to search for information on what you’re trying to do in the API:

Specific interface/method search terms – This is, of course, only possible if you already know which specific interfaces or methods you’re looking for. Either you’ve used that specific item before, or you’ve run across something captured by the macro recorder (for more on the macro recorder, see the eLearning API webinar) that you want more information on.

Descriptive search terms – This means searching based on how you would describe what you’re trying to do in normal English. For example, you might search “save file as dxf” or “get material properties.” The search will usually return some examples that contain interfaces or methods that you can then specifically search for, or in some cases will take you more directly to an article for an interface or method that addresses that topic. 

 

 Once you find an article that seems like it might be useful, it’s important to note which category the article falls into:

1. Interface

If the subject of the article is described as an interface, think of it as an umbrella object that must be implemented in order to gain access to the functions that it contains. In every “Interface” article, there will be a section called “Accessors.” This tells you how to create an instance of this interface so that its functionality can be used within your macro.

For example, the IModelDoc2 interface lists “ISldWorks::ActiveDoc” as one of its accessors. This means that in the top level SldWorks interface, there is an “ActiveDoc” method that returns a ModelDoc2 object. Thus, in order to “reach” ModelDoc2 and use its functions, you have to go through swApp.ActiveDoc or one of the other accessors. The implementation of the code looks like this (something we’ve seen a few times in previous posts already):

Dim swApp As SldWorks.SldWorks
Set swApp = Application.SldWorks

Dim swModel As ModelDoc2
Set swModel = swApp.ActiveDoc

Each interface article will also have a link to “(Interface name) Members.” This is a complete listing of the interface’s properties and methods that you can call to actually do useful things.

2. Method

These are the items that will actually perform useful actions. Methods (also called functions) may contain one or more parameters that must be defined as input in order for the method to execute properly. For example, the FeatureExtrusion2 method has a list of 22 parameters (see picture below), ALL of which must be defined in order for it to execute properly. The Help File’s listing and description of the different inputs, what they mean, and what data type they require (Integer, String, Boolean, etc.) is a much more reliable resource than your memory.

 

 

One tip on using parameters in VBA: When you’re calling a method and assigning its return value to a variable, the parameters must be enclosed in parentheses. Otherwise, no parentheses are necessary.

For example, the CustomPropertyManager interface contains an .Add2 method that adds a new custom property to a SolidWorks document. The return value for .Add2 is the integer 1 if the property was successfully added and 0 if it was not. If you want to use this return value later (as in, execute or skip portions of the code based on whether that property was added successfully), you would want to store the return information from .Add2, and its parameters would have to be enclosed in parentheses as follows:

AddStatus = CusPropMgr.Add2(“Property Name”, swCustomInfoText, “PropertyValue”)

However, if you don’t care about keeping track of whether the property was added successfully, you could just use the following line of code:

CusPropMgr.Add2 “Property Name”, swCustomInfoText, “PropertyValue”

Note that the parameters are simply added after a space following the method call. Using parentheses in this case would return an error.

3. Example

The Help File contains many useful examples in various languages (not just VBA) that can help guide you in the right direction. These examples will generally use one or two key functions that you can specifically search for in order to understand how to put them into some new context that’s more useful for what you’re trying to accomplish.

When searching through the Help File, make sure you pay attention to any messages about methods being “Obsolete. Superseded by ___________.” Methods that are obsolete may still work, but they might be buggy or more limited than newer versions. Using the latest version is generally a good idea.

 If you’re interested in the SolidWorks API, make sure to check out the recorded webinar: “Introduction to the SolidWorks API”.

See the previous posts from this series:

Getting Started with the SolidWorks API - Part 1

SolidWorks API Building Blocks - Part 2

SolidWorks API Building Blocks - Part 3

Commonly Used Interfaces in the SolidWorks API - Part 4

Commonly Used Interfaces in the SolidWorks API – Part 4

In the previous post, we discussed the SolidWorks Object Model and how its hierarchical structure impacts the way you access API functionality. But how do you find what you need within the hundreds of interfaces and functions within the API? Fortunately, you don’t need to know all – or even most – of the API in order to start doing useful things. Here are some commonly used interfaces and functions that will get you up and running:

1.  ISldWorks

The top-level SldWorks interface is accessed automatically when a new macro is created. The auto-generated “Set swApp = Application.SldWorks” line makes this initial connection and gives the macro access to doing things like opening, closing, creating, and saving documents, turning toolbars on and off, and loading and unloading add-ins. Almost anything you want to do within the SolidWorks application requires first connecting to the ISldWorks interface.

2.  ModelDoc2

The IModelDoc2 interface is exposed by the ISldWorks interface. This interface (also referred to as the ModelDoc2 object) gives the macro access to things like rebuilding a document and adding configurations. ModelDoc2 also exposes several other interfaces (see below) that can be used create and modify features and sketches.

The following is an example of an implementation of the ModelDoc2 object:

Dim swApp As SldWorks.SldWorks
Set swApp = Application.SldWorks

Dim swModel As ModelDoc2
Set swModel = swApp.ActiveDoc

In this example, the variable swModel is used to store a reference to the active SolidWorks document’s ModelDoc2 interface. This step isn’t always strictly necessary, but typing swModel.function is easier than having to type out swApp.ActiveDoc.function every time.

3.  IModelDocExtension

The ModelDocExtension object is, as it sounds, an extension of the ModelDoc2 object. ModelDocExtension was created because objects have a limited number of methods and properties that are allowed. The ModelDoc2 object reached its capacity, so the SolidWorks software engineering team created ModelDocExtension to define more things that would otherwise belong to ModelDoc2.  ModelDocExtension is exposed by the IModelDoc2 interface, meaning that it is accessed in the following manner:

Dim swDocExt As ModelDocExtension
Set swDocExt = swModel.Extension

These statements assume that swModel has been declared as a ModelDoc2 object and assigned to a valid SolidWorks document (both of which are done in the previous example). ModelDocExtension controls functionality like adding custom properties, getting mass properties, and adding BOM and revision tables.

4.  IFeatureManager

The IFeatureManager interface is exposed by the ModelDoc2 object, just like the IModelDocExtension interface. This means that its implementation is almost identical:

Dim swFeatMgr As FeatureManager
Set swFeatMgr = swModel.FeatureManager 

The FeatureManager object controls things normally done in the Feature Manager Tree when using the graphical user interface. Examples include editing and creating features, hiding and showing solid bodies, and changing the rollback state of the Feature Manager Tree.

5.  ISketchManager

As the name suggests, the SketchManager object allows your macro to access sketch tools for creating sketches and sketch entities. It is also exposed by the ModelDoc2 object, so its implementation looks something like this:

Dim swSketchMgr As SketchManager
Set swSketchMgr = swModel.SketchManager

Hopefully, this short list of commonly used interfaces gives you a better sense of how the SolidWorks Object Model is organized and what terms you might need to search for in the API Help File to find more functions to use. We’ll discuss the API Help File in greater detail in the next post, but for now you can search the API Help File for “_______ interface” (fill in the blank with one of the interfaces above) and see the first search result for a full list of properties and methods that you can access through each of the above objects.

If you’re interested in the SolidWorks API, make sure to check out the recorded webinar: “Introduction to the SolidWorks API

See the previous posts from this series:

Getting Started with the SolidWorks API – Part 1

SolidWorks API Building BlocksPart 2

SolidWorks API Building Blocks – Part 3

 

SolidWorks API Building Blocks – Part 3

Basics of the SolidWorks Object Model

In the previous post of this blog series on the SolidWorks API, we discussed the four lines of code that get generated automatically whenever we start a new macro. So where do you go from there? Most commonly, we’ll then connect to the active SolidWorks document or open a new or existing SolidWorks document. We can access these things using statements of this type:

swApp.ActiveDoc

swApp.NewDocument(parameters)

swApp.OpenDoc6(parameters)

We’ll discuss parameters in a later post, but notice that before we call each function, we specify “swApp.” In order to access functions, we need to specify to the code where these functions are coming from. In the case of these first few functions, they all belong to the top level SolidWorks application. Usually, you’ll also want to do something with the document, such as get some information about the geometry, add custom properties, or traverse the feature tree. Thus, it’s helpful to store the newly created/opened/accessed document into a variable. Our statements would then look like this:

Dim swDoc As ModelDoc2

Set swDoc = swApp.ActiveDoc

Recall from the previous post that the “Dim” statement is used to declare a variable in which to store some type of data (in this case, a ModelDoc2 object), and that swApp is the variable commonly used to store a pointer to the SolidWorks application.

In this case, what we’re doing is declaring the swDoc variable as a ModelDoc2 object (an umbrella object that encompasses parts, drawings, and assemblies) and then taking whichever document is currently active in SolidWorks and assigning its address to the swDoc variable. By declaring swDoc as a ModelDoc2 object, we have access to all the functionality defined in the IModelDoc2 interface (see the API Help File and browse to SolidWorks API Help -> SolidWorks.Interop.sldworks Namespace -> Interfaces -> IModelDoc2).

The SolidWorks Object Model extends far, far beyond what is shown here, but it is helpful to have a visual representation of the basic structure. The implication of the Object Model’s structure is that we have to access features through the specific interfaces that are defined by the API.

For example, under the IModelDocExtension interface, there is an “InsertBomTable2” method that creates a Bill of Materials table in an assembly or drawing document. However, we can’t just drop “InsertBomTable2” into our code and expect the program to figure out what we want.  We have to start from the “SldWorks” application object, then go to a ModelDoc2 object, then go to that object’s ModelDocExtension interface, and then finally call the InsertBomTable2 method. The actual code to do this would look something like this:

Dim swApp As SldWorks.SldWorks

Dim swDoc As ModelDoc2

Dim swDocExt As ModelDocExtension

Sub main()

Set swApp = Application.SldWorks

Set swDoc = swApp.ActiveDoc

Set swDocExt = swDoc.Extension

swDocExt.InsertBomTable2 parameters

End Sub

Actual execution of the above code would require proper parameters to follow the swDocExt.InsertBomTable2 function call. Again, we’ll talk about how to figure out the parameters of functions from the Help file in a later post.

If you’re interested in the SolidWorks API, make sure to check out the “Introduction to the SolidWorks API” webinar.

See the previous posts from this series:

Getting Started with the SolidWorks API - Part 1

SolidWorks API Building BlocksPart 2