solidworks vba create 3d sketch draw lines
This mail is nearly how to create, edit and debug SOLIDWORKS macros when yous are completely new to building software.
We'll record a unproblematic macro, explain the code and make clean information technology upwards. And so we explain how you lot can debug your own macros.
You lot don't need to exist a software engineer by profession to be able to create macros, only a basic agreement of programming will help. I myself am a mechanical engineer by trade. I merely started coding professionally when I started CAD Booster in 2017.
In this mail service, you'll notice
- What is a macro?
- What is an add-in?
- How to tape a SOLIDWORKS macro
- VBA editor: what is the firsthand window?
- Explaining the recorded code
- Improving the recorded code
- Checking the model blazon to prevent errors
- How to debug VBA SOLIDWORKS macros
- How to pick a language
- Sources and courses
one. What is a macro?
SOLIDWORKS has 2 flavors for automation: macros and add-ins. Macros are the nigh attainable, so we'll outset 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 tin sit down anywhere on your figurer. You lot can run the macro past browsing for it or by calculation a shortcut button to your command manager in SOLIDWORKS..
You tin even tape and play dorsum macros, although not all deportment tin can be recorded.
The advantages of macros
- Relatively easy to get started with.
- SOLIDWORKS contains an editor to create and edit macros.
- Tin be created in VBA (Visual Basic for Applications), VB (Visual Basic, formerly VB.net) and C#.
- You tin can quickly create a new macro. By at present, I can build a simple macro in two minutes.
- If you are familiar with macros in Excel, you can reuse much of that knowledge.
- You tin run them in a batch tool similar #Task, although I'm not a big fan of that product.
The disadvantages of macros
- The forms look ugly and grayness unless yous put in some real work.
- You cannot create task panes (those tabs on the correct).
- Y'all cannot do proper version control because the SWP file is not a text file. Version control software like Git tin can therefore not see what you lot have changed, only that the file has changed.
- Information technology'southward difficult to roll out updates because:
- Files tin become locked when y'all admission them with multiple people. I've heard people say they had to wait till everyone went home to update the macro file.
- When anybody has their own file, you are never certain everyone is using the aforementioned version.
two. What is an add-in?
If you want to make a professional product that integrates with SOLIDWORKS, you lot need to build an add-in.
With add-ins, you can create Property Director Pages (PMPs, those menus on the left, that let you edit Extrude properties, for example) and task panes (the carte du jour tabs on the right).
Add-ins are commonly installed on your computer with a Windows installer. After that, your new add-in appears in the list of available add-ins:
Add-ins can exist built by SOLIDWORKS (like SOLIDWORKS Routing) or past third parties like CAD Booster. Nosotros 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
- Completely integrated within SOLIDWORKS.
- You can create them in whatever programming language that supports COM. Frequently used languages are C#, C++ and Python.
- Allows you lot to create task panes and property manager pages.
- You can create your own user interface (with WPF, for case) in the job pane. There'southward no demand to use the ugly grayness user interfaces from xx years ago from Windows Forms.
- You lot tin do proper version control (with Git, for example) considering the source code is stored in multiple text files.
- Users tin easily install add-ins and their updates with an installer.
The disadvantages of add-ins
- In that location is a steep learning bend if y'all have never built software before, or if you take never built software for SOLIDWORKS earlier.
- You need external tools similar Visual Studio to develop the software.
- Yous need to compile your code and create an installer.
Overall, nosotros 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 past recording your ain actions using the macro recorder.
Prepare your model file, hit record and but perform the deportment that you desire to record. Hit stop to save the file.
This bang-up video by GoEngineer shows y'all how to record your actions and let SOLIDWORKS catechumen them into a macro. Y'all tin can then create a push button in your toolbar to run the macro whenever you need it again.
SOLIDWORKS does not tape all of your actions, though. This is confusing and abrasive for people that are but getting started. So don't be surprised if your action does not bear witness up in the macro. Simply be disappointed 😉
The macro recorder does record most deportment that create geometry or features. Information technology does not tape many of the clicks in the user interface.
four. VBA editor: what is the firsthand window?
I have recreated the actions in the video above and saved the result. Clicking the rightmost button in the macro toolbar opens upward the Microsoft Visual Basic for Applications editor. In my instance, it looks similar this.
The window has five sections:
- Upper left: Project Explorer.
- Here you can find the modules, user forms, grade modules and SOLIDWORKS objects in your macro. Right-click to add together whatever one of those things.
- Lower left: Properties window.
- When y'all select an element in a UserForm, this section shows the properties of that element.
- The big one in the center: your main window for the code.
- Lower center: Immediate window.
- You can write text to this window for piece of cake debugging. The text volition stay there until you lot manually select and delete it.
- Lower right: Watches.
- You lot can right-click a variable and add a lookout to it. When yous step through the macro with a few lines at a time, yous 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 yous a list of the variables in your lawmaking and their electric current values.
If you lot don't see a certain window, click View at the top to enable the missing window.
5. Explaining the recorded lawmaking
I added numbers in red to the previous paradigm to explain the code.
I've written down everything that is happening in this short macro, everything that does non make sense and everything that I remember you should know.
- A line that starts with a single quote ( ' ) is a comment
- Commented lawmaking will not be executed.
- It is good practice to commencement your macro with a few lines on the who, why and how.
- Yous tin can comment out part of a line. Anything on a line after the apostrophe is ignored.
- The variable chosen swApp is created, or defined.
- Information technology starts with Dim, a standard give-and-take to create a dimension new variable, and so its name, as and its blazon.
- This variable is used in every SOLIDWORKS macro and about people telephone call information technology swApp to be able to read each others' lawmaking hands.
- It starts with a prefix (sw) to help you understand its type (a SOLIDWORKS object). This way of working is chosen Hungarian notation and it has gone out of style by at present. Notice how it is used for longstatus (type = long) and longwarnings as well.
- The rest of the proper name is a user-friendly name. In this instance, app is short for application, the SOLIDWORKS awarding itself.
- The variable type is object, which means it tin can basically incorporate anything. Information technology is better to pick a more narrow variable type so cannot put incorrect data into the variable.
- If your object has no value yet, information technology is nothing. When y'all then try to do anything with it, you lot get the cryptic error message Object variable or with block variable non set.
- If y'all define a variable outside of a sub or function, you can access information technology everywhere in your macro. Information technology's a global variable. This sounds great, but you should avoid using these equally much every bit possible.
- Other variables are defined
- Every bit you can, see you can define multiple variables on i line
- If you lot don't specify a blazon ("Dim swApp"), the variable will be a variant.
- Variants are strange types that can contain any type of data, but y'all need to convert them to specific types if you want to do some real work with them
- Variants are required for for each loops.
- The subprocedure called master is created.
- Everything until the Cease Sub at line 19 is a part of the main subprocedure.
- The brackets latermain can comprise variables, called arguments or parameters, that this subprocedure needs to role. 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 chief, whatever subprocedure may be called. That is not what you want, so keep Main as the starting point.
- The swApp variable is set to the current SOLIDWORKS application then that our macro can talk to SOLIDWORKS.
- The underscore _ is at that place for no reason at all. It allows you lot to create long lines of lawmaking that are on multiple lines. You tin safely remove the underscore and the enter so the line becomes ready swApp = Awarding.SldWorks
- If y'all are working with an object, yous need to start the line with ready, followed by the variable name, an equals sign and its new value.
- If you are working with a value typelike a cord, integer (a whole number) or a double (a double-precision decimal number), don't use the word set.
- The Office variable is set to the document that is currently open
- Part is a really poor variable proper noun hither, because the active model may be a part, drawing, assembly or nothing.
- Its actual type is ModelDoc2.
- Notice that nosotros go the function object from the swApp object. Objects have properties and methods. The active model is a property of the SldWorks object.
(I repeated the image to make the mail service more than readable)
- Because the variable Part is assigned the active document, you lot can at present call special SOLIDWORKS functions (also named methods).
- Add a dot after a variable proper noun to see all available functions. If you don't run across whatever options appear, your object is probably but that, an object. Use a more specific blazon like SldWorks.SldWorks or ModelDoc2 to see more options.
- Right here nosotros employ the method InsertSketch to start a sketch on a pre-selected surface.
- If y'all call a method that needs parameters, and you lot want to shop the return value, y'all need parentheses around the arguments. Run across line xv.
- If yous practise not store the render value of a method or the method has no parameters, yous need no parentheses. VBA allows both, which is confusing for beginners and annoying for experts.
- 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 sometime version so they don't suspension older macros. The old method is now called Obsolete.
-
- If anything was selected earlier the macro was started, it is deselected with this method call.
- A new sketch segment variable is defined
- Considering this variable is defined within a subprocedure, it is called a local variable, which means that it tin only be used inside this subprocedure.
- The variables declared at the elevation at 2 and 3 can be used from anywhere and are chosen global variables.
- A circle is fatigued by the coordinates of the center point and 1 other betoken on the circle.
- This line actually chains multiple objects.
- It uses the Part object (the active model), then its SketchManager object (an object that lets you lot create and edit sketches) and calls the CreateCircle method.
- The option is cleared once more
- InsertSketch is chosen again, this time to close the sketch
- The sketch is opened again.
- The pick is cleared once more, this all seems pretty useless.
- The sketch is selected
- A new variable that tin agree a feature is defined
- A new characteristic is created using the selected sketch and a whole lot of options.
- Don't even carp trying to recollect all options. The help page will tell you what those options are. I visit the API Help every single solar day.
- EnableContourSelection can be used to select the contour of the sketch for the cutting extrude.
- Nosotros don't demand that option anymore, so information technology can be disabled. Notice it wasn't enabled in this code, so it is probably enabled by default.
- The chief subprocedure is closed.
- You can take multiple subprocedures and functions. I fact, it is a good do to try to limit each role and procedure to about x lines of code.
- Officially, a subprocedure returns no value and a function does. You can, nevertheless, create a function that returns no value
- To create a function that returns a value, typeas and a type afterward the function'due south brackets. Case:Role ReturnModel() as ModelDoc2.
- To set the value that you want to return, use the proper name of the role. If you return an object, start with ready. Example:set ReturnModel = swModel.
6. Improving the recorded code
The output from the macro recorder is far from great.
It does non even apply all variables and some lines are in there way too many times. Fourth dimension to clean it up. This is what information technology can look like afterwards.
Equally you can see I take:
- Moved the variable declarations to the acme of the program for clarity (2020 update: don't create a long list of all variables at the summit 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 practise annihilation.
- Gear up the draft angles of the feature to nil instead of 1.7451558415E-02. Ii of the 'false' statements were to disable a draft anyhow.
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 mail in 2020, I would make even more changes:
- I would move the global variables into the subprocedure. No globals unless we actually need them.
- I would remove longstatus and longwarnings because they are never used.
- I would remove boolstatus if we don't need its value after calling SelectByID2. We and then need to remove the brackets effectually the parameters.
- I would rename OfficetoswModel and make it of type ModelDoc2. The naming is the convention in SOLIDWORKS macro land. The Part blazon is too restrictive because the model can besides be an assembly.
- I would renamed myFeature to swFeat, likewise a convention.
- I would declare my variables just earlier I need them. This makes it easier to find out their type and makes it easier to spot problems. List all of you lot variables at the top is and old C++ convention that we don't need here.
seven. 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 y'all did not wait 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 tin can get the active model.
| dim swApp as SldWorks . SldWorks fix swApp = Applcation . Sldworks Dim swModel as ModelDoc2 set swModel = swApp . ActiveDoc if swModel is nothing so Msgbox "Delight open a model first" End Cease if |
Getting swApp never goes wrong. Just if not model is open, swModel will be null. 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 piece of work with the ModelDoc2 object, you don't need these checks. But when you lot desire to call methods that are but available for function, assembly or drawing objects, you need to verify the agile model type. To brand sure the model is a role:
| 1 2 three 4 5 6 7 8 ix ten eleven 12 thirteen fourteen 15 16 17 | dim swApp equally SldWorks . SldWorks set swApp = Applcation . Sldworks Dim swModel as ModelDoc2 prepare swModel = swApp . ActiveDoc if swModel is nothing and so Msgbox "Please open a model first" End End if if swModel . GetType <> swDocumentTypes_e . swDocPART then Msgbox "Please open a part get-go" End End if 'Perform the bodily work here |
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
In that location are a few options that you should know when you want to properly exam en debug your bits of lawmaking:
Step by step
Y'all can execute your code until a certain signal by setting your cursor where it needs to break and click Debug > Step into or press F8. The code runs until information technology reaches this indicate. From there you tin can run it line by line by pressing F8, this is a nifty way to debug your own code or to get to know another macro.
Pressing F5 calls the run control and runs the macro until the finish or until you reach a breakpoint.
Breakpoints
By left-clicking earlier a line, y'all 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 yous've assigned watches to.
Pressing the play push volition arrive hop until the next breakpoint, striking end volition make it terminate immediately.
Debug.Print [variable name]
This line adds the contents of ane 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
Debug.Assert [variable name] [condition]
The line Debug.Assert 10 > 10 volition affirm whether x is indeed greater than ten and it will intermission the program if information technology isn't.
Telephone call stack
The last tool for debugging that I want to mention is the Call Stack choice.
When the lawmaking execution is started and paused, you lot tin can press View > Call Stack or Ctrl + L to see how the current role 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 tin can write macros in three Microsoft-based programming languages. The first i is Visual Bones for Applications (VBA), of which you have seen a lot in a higher place.
Information technology is easiest to starting time with VBA because it is the nearly attainable option. The help website past SOLIDWORKS is likewise extensive and sorted by version.
VB (which used to be called VB.NET) and C# are the other two options. These are the more than modern and more advanced options. They also permit you to create add together-ins for SOLIDWORKS, this isn't possible with VBA.
10. Sources and courses
Here are some useful sites when you lot want to get started with building macros for SOLIDWORKS:
- The official SOLIDWORKS API Help and specifically, the section on macros.
- The official SOLIDWORKS forums, where I regularly hang out.
- Microsoft Function VBA reference
- CADSharp.com has many free videos and macros to learn from
- AngelSix has ii (rather dated, but yet useful) freely available SOLIDWORKS books and many macros. He also has videos on C# and add-ins.
- Nosotros have great articles well-nigh matrix transformations in SOLIDWORKS and most How to improve macro speed 10x.
Doing a Google search in the form of SOLIDWORKS API [your search term] will also do miracles. I practice that a dozen times per 24-hour interval.
If you desire some professional guidance in your endeavors, y'all tin can enroll in this form past SOLIDWORKS:
- API Fundamentals Course
Your electric current Value Added Reseller (VAR) can assist you with official SOLIDWORKS courses.
11. Or just let united states build you a macro (or add together-in)
I started CAD Booster 4 years ago to automate the boring bits of my engineering chore. Since then, I accept created add-ins similar Drew and Lightning, plus a dozen others for our customers.
Considering of all that experience, I know my way around the SOLIDWORKS API. So a macro that might take yous days can sometimes take me only 30 minutes.
I will usually advise you lot to develop an add-in because they are more than stable and can be maintained properly, just I also just finished a macro for a customer.
Check out the Contact page for our email address and telephone number.
12. Final words
Are y'all excited to build a simple plan that can take over some of your daily tasks? I'thousand pretty sure at that place are some great ideas out in that location.
At present permit's get those niggling robots to do our chores!
Source: https://cadbooster.com/macros-for-solidworks-the-absolute-basics/
Postar um comentário for "solidworks vba create 3d sketch draw lines"