SolidWorks Design Automation Using the SolidWorks API, Microsoft Excel and VBA
Upcoming SlideShare
Loading in...5
×
 

SolidWorks Design Automation Using the SolidWorks API, Microsoft Excel and VBA

on

  • 13,053 views

Design Automation Techniques (session 2) with SolidWorks 2009 and 2010, Excel and VBA - Presented to Greenville (SC) SolidWorks User Group September 15, 2009 @ CU-ICAR

Design Automation Techniques (session 2) with SolidWorks 2009 and 2010, Excel and VBA - Presented to Greenville (SC) SolidWorks User Group September 15, 2009 @ CU-ICAR

Statistics

Views

Total Views
13,053
Views on SlideShare
12,279
Embed Views
774

Actions

Likes
1
Downloads
225
Comments
0

9 Embeds 774

http://www.razorleaf.com 535
http://razorleaf.com 200
http://www.slideshare.net 31
http://www.slashdocs.com 2
https://razorleaf.com 2
http://betasite.razorleaf.com 1
http://translate.googleusercontent.com 1
http://www.docshut.com 1
http://www.razorleaf.com.php53-26.dfw1-2.websitetestlink.com 1
More...

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • First of all, are you in the right place? We’re here to talk about design automation with SolidWorks. So whether you use a commercially available Solution Partner product like this…
  • Or like this…
  • Or maybe you’re using one of these…and if you’re not, feel free to check them out in the partner pavilion. I hear that they have lots of free stuff. Maybe they’ll even raffle off one of the people from their booth.
  • Or maybe you run your automation from in here…
  • Or maybe you do it right inside here…
  • Or maybe you’re hardcore and you use this…Or maybe you don’t even know what this is…
  • Either way folks, I am here to tell you that you have come to the right place.
  • This is what we’re really talking about. We know how to design with SolidWorks and to use it as an interactive tool to build strong designs, but I do want to stress here that this session is listed in the DESIGN AUTOMATION technical track, and we are concerned about how to use SolidWorks in the context of a design automation. This is important because the folks at SolidWorks spend countless hours, days, months, (years even!) developing better and faster ways for you to interact with SolidWorks. With automation, you want to try to make it so that people DON’T interact with SolidWorks. So there are some tricks to it, and that’s why you’re here…I hope.
  • So what I’m really saying is that when it comes to calculations, SolidWorks is just faster than I am. My general rule of thumb is “Thinking…bad. SolidWorks…good.” I’m not saying that an engineering education is a waste of time. I mean my years trapped in New Jersey were actually quite valuable. Where else would I have learned such invaluable skills as:
  • The social and personal importance of competitive sports, alternative uses for common household items (I think this is how MacGyver started), the importance of nutrition and the availability of over-the-counter productivity products, and cooking techniques that would make Rachel Ray curl up in the fetal position. It’s not that when I’m designing an automation, I don’t need to think. That’s what I get hired for. People certainly don’t pay me for my good looks…[Don’t laugh at that/Thank you for not laughing at that.] There are some times when it’s just not worth racking your brain when SolidWorks can do it so much faster and easier.
  • When people do engineering process automations, they’re primarily looking for one of a few things. Most often they want to drive SolidWorks to get drawings or models for production, sales, approvals, what have you. Oftentimes, they’re looking to guide people through the process to guarantee that they don’t specify (or sell) something that just won’t work or cannot be manufactured. That’s typically done by simply limiting their choices to combinations that you know work or provide limits to work within. Sometimes, people use the automation to actually capture engineering knowledge and have the system apply it to determine the feasibility or performance of a design. In these cases, the automation system is taking the questions that would typically be asked of Engineering, “What’s going to be the output torque at the shaft for these inputs?”, “How much is this thing going to weigh?” or to get costing and therefore pricing. This frees up Engineering to get back to what we do best, very creative rubber band fights, switching the regular and decaf in the executive coffee machine, making snide comments about the sales and marketing folks. Oh yeah, and designing new products.So in these three areas, we can have some math to do. And in some cases, that’s pretty easy. “How big is that? OK, length times width divided by a full sheet gives you the sheet usage percentage times the material cost and there you have it.” But in other cases, we can get geometry that’s tough or laborious for us to generate repetitively, even with SolidWorks. Sometimes, determining form, fit and function require a bit of SolidWorks knowhow. And calculations can often involve complicated components like moments of inertia, clearance distances, or weights that are tough of figure out.
  • Here are some of the types of applications where you might want to utilize SolidWorks for calculation purposes inside of an automation. And we’ll go ahead and look at these further.
  • So the first type of examples for where we can leverage SolidWorks in an automation is when we have complex geometry or geometric systems that need to be solved. SolidWorks does these very quickly and efficiently. Quite often, in my implementations, we simply drive a sketch in SolidWorks to get our answer. In many cases, like a linkage, or a truss, there’s no reason to even build solid geometry. In these cases, we drive the geometry of the system and in return, we get back something that we were missing about that geometry. Whether it’s the travel of the damper in the bike linkage for a given frame geometry or the total length of the serpentine belt, we want to talk about how to give SolidWorks what we know and get out what we need to know.
  • Manufacturability is coming up more and more as people realize that they can do this up front. DFM has been around for years, but how often in the quoting process do you consider which machine you’re going to run a part on or what the standard stock sizes are? DFA teaches us to look for tool clearances and ensure that the design is shop friendly, but can we really do that right up front? Absolutely. If we can look at it to make that determination, SolidWorks should be able to look at it for us and let us know.
  • Here’s another one that I just would not want to figure out long hand. How far apart are these two features/faces/bodies. Do they interfere? If so, then I need to know now, so I can tell the user it can’t be built before some salesperson runs off and sells it. I have clients that design by putting these two parts between this far and that far from each other. How do you do that in SolidWorks? You either place it in the assembly, leave it under-defined, and drag it with a clearance check, or you sit there and slide the sliders in the modify boxes until you get a solution that works. The problem is that you just can’t drag in an automation. So we’ll look at the use of iterative solving with SolidWorks.
  • This goes along with complex geometric problems. You can use a combination of automation power and intelligence and some of the tools like equations and relations in SolidWorks to solve problems that would be otherwise next to impossible.
  • Validation is the primary role of Engineering in the presales process. When sales is selling a product, they don’t need us to design it. They just want to be able to say, “Well, Rachel said the design was fine.” We, on the flip side, want to avoid the inevitable problems that we’ll have to solve, figuring out how to shove 48 cubic yards of manure into an Altoids box. By automating this and bringing it up front, we identify the problem areas immediately and either eliminate bad designs, or get REAL engineering intervention to solve custom problems into the process much earlier. But this isn’t confined to problems. People also need or want to know predicted performance for a system before it’s even designed. Cervelo P4 Time Trial/Triathlon bike. It needs to be light. How light, 6.8 Kilograms. That’s the minimum weight for a Tour de France bike. Yes, I said minimum. So they have a target. But they also need to reduce frontal area and drag and they also need to maximize stiffness. If they know the rules, they can let SolidWorks figure out the what the performance characteristics are going to be before they build my custom frame.
  • TDAM has always been one of the selling points of SolidWorks and when it comes to automation, we love it too. How big of a box DO you need for 48 yards of mulch? What’s it really going look like when those parts intersect? Why bother figuring out where the same hole goes twice, just because it’s on two different parts. Again, we’re interested in making it non-interactive, so that we can let our programs do the talking, but there is still a lot of TDAM that we can leverage.
  • OK, let’s see how to do all of this. One disclaimer…All of the code (and yes, it’s available for your reading pleasure) will be made available at the end of the presentation (call it my insurance that you’ll stay) and it is all in Excel VBA. Why VBA? It seems to be the most pervasive way to code. Just about everyone has Excel. Plus, if you can code in C#.NET, then reading the VBA will be a piece of cake for you. Plus, I’m not a real code monkey. I’m a mechE.
  • Second disclaimer: You’re not going to see all of the code in this presentation and I’m not going to break it all down for you. I’m here to talk about applying fairly high-level concepts. I will show you details on some sticking points, but if you want to learn syntax, you can also go to see Jerry Winters do his sessions and check out the API Help file in SolidWorks. One problem here is that I just got done telling you how I’m using Excel VBA, which is essentially VB6, for this presentation and the help file in SolidWorks 2009 has been completely revamped to discourage you from using VB6. It is almost exclusively focused on .NET syntax with VB6 as a bit of a footnote. All of the VB6 examples, however, are still in there, but the syntax and descriptions are a lot less helpful. If you know anyone at your company that still has a SolidWorks 2008 installation, I would recommend that you steal the API directory in there and archive it. You can run the CHM file right from Windows Explorer and it’s a lot more VBA friendly.
  • And disclaimer #3. You’re not going to see me do any coding live. I’ve been to every SolidWorks World. And I have yet to see a session where the presenter codes live and it works. They waste a ton of time looking for where they types “END OF” instead of “END IF” and then the code still doesn’t work and there’s that awkward time when you’re thinking “Just give up and move on.” Then there’s the SolidWorks crashes. Well my code isn’t going to crash. You can bet on it. This is pure PowerPoint. And I KNOW that excites you. OK, now on with the show.
  • So here is our first example. Southern States Superior Spring and Scissor Lift Systems manufactures custom designed lift systems for companies all over the world. The client provides the application information including the size and weight of the load, the starting and ending heights and whether they’re going to pay with cash or credit card, and the Southern States Superior Spring and Scissor Lift sales specialists specify safe systems to satisfy specific situations. Internally, engineering needs two things. First, they need good, complete information for systems that can actually be manufactured. Secondly, they need to determine the linkage lengths so that they can determine linkage and pin sizes to avoid shearing and other modes of catastrophic failure. And by catastrophic, I mean catastrophic to the engineer’s career. So how do you approach such a situation?
  • Well, this is how we do it. And incidentally, this is how we do every design automation involving SolidWorks. It’s a fairly simple process of collecting your inputs, passing them to SolidWorks, retrieving info back from SolidWorks and continuing along your way. Let’s look at it in a bit more detail.
  • First we collect the inputs. Again, this is one place where Excel shines. If you’re using a commercially available solution partner, then that will be the vehicle for creating your user interface. If you are NOT using a solution partner product, I wholeheartedly encourage you to go speak to them in the partner pavilion. I believe that most of them are there and the word on the street is that they’re giving away lots of free stuff and I think one of them is raffling off one of their employees. So that may or may not be worth something. But definitely hear them out, they are generally a lot faster than doing it in pure code and a lot more maintainable.If you DO want to do it in Excel, however, please go to www.razorleaf.com, click on the presentations link and download the presentation from last year on doing automation in Excel. There’s lots of good information in there and it’s reasonably priced. OK, fine. It’s free. And for the moment, I don’t even think we ask for your name. So we’re trying to educate the community, not build our marketing list.Lots of good info in that session that I will NOT go over, but the one thing that I WILL stress is that you should always name your cells. If you do, your Excel formulae will be much more readable and your code will as well. If you don’t know how to do it, just click here and type away. You can also go to Insert->Name in older versions of Excel. In Excel 2007, it’s called the Name Manager and it’s on the Formulas ribbon.
  • Once you have your input data, or even as you’re collecting it, you can do some calculations. Anything arithmetic or logical that your brain can handle, do it here. The primary benefit is that it will generally get calculated live and can provide instant feedback that can validate the inputs and prevent users from entering in bad numbers. And even if they cannot be done live, this portion of code should be the area that converts units and otherwise processes the values to be SolidWorks-ready.
  • Before sending values to SolidWorks we need to invoke its holy name. At this point, we start working with what can almost be called object-oriented programming. I say almost because if there are any .NET programmers here, they would come up afterwards and lecture me for a full hour about how VB6 does not fully implement polymorphic instantiation of friend classes or something like that. But the point is that we’re dealing with objects here. For a primer on Object Oriented Programming to the extent that Excel handles it, check out the aforementioned presentation on the Razorleaf web site.Now connecting to SolidWorks is fairly easy, and in fact there are several ways to do it. I’ll only show you one because it’s the best and I don’t want you to call me to help you troubleshoot code that you wrote using the others. Again, we’re dealing with object here, so the first thing that we need to do is to link to the SolidWorks Object Definitions (which are called classes) and they live in the SolidWorks Type Library. So grab them from TOOLS->REFERENCES in your Visual Basic for Applications environment. If you’re working in .NET, you still need to grab references, but they are the newest SolidWorks Interops. The one that you will need is the SolidWorks.Interop.SldWorks Namespace. And you’re going to want to throw a letter I in front of all of the classes to get your interfaces. VBA folks, you will also want to grab the SolidWorks Constant Library as well. That will make your life easier.Once you have your references, you need to create an object to hold the SolidWorks application and dim it as SldWorks.SldWorks. Not as OBJECT. Not as Variant. Put that Option Explicit up there and make sure that you fully qualify everything. To instantiate your application, you use the Windows CreateObject function. CreateObject is cool because it will start SolidWorks only if it’s not already open. If it is open, it will latch onto the open process. Once you have the SolidWorks application object, you need the second component, which is the SolidWorks ModelDoc2 object. You have some functionality within the application, like the ability to open a file, but the majority of the functionality lies in the ModelDoc2 object and its children.
  • Before sending values to SolidWorks we need to invoke its holy name. At this point, we start working with what can almost be called object-oriented programming. I say almost because if there are any .NET programmers here, they would come up afterwards and lecture me for a full hour about how VB6 does not fully implement polymorphic instantiation of friend classes or something like that. But the point is that we’re dealing with objects here. For a primer on Object Oriented Programming to the extent that Excel handles it, check out the aforementioned presentation on the Razorleaf web site.Now connecting to SolidWorks is fairly easy, and in fact there are several ways to do it. I’ll only show you one because it’s the best and I don’t want you to call me to help you troubleshoot code that you wrote using the others. Again, we’re dealing with object here, so the first thing that we need to do is to link to the SolidWorks Object Definitions (which are called classes) and they live in the SolidWorks Type Library. So grab them from TOOLS->REFERENCES in your Visual Basic for Applications environment. If you’re working in .NET, you still need to grab references, but they are the newest SolidWorks Interops. The one that you will need is the SolidWorks.Interop.SldWorks Namespace. And you’re going to want to throw a letter I in front of all of the classes to get your interfaces. VBA folks, you will also want to grab the SolidWorks Constant Library as well. That will make your life easier.Once you have your references, you need to create an object to hold the SolidWorks application and dim it as SldWorks.SldWorks. Not as OBJECT. Not as Variant. Put that Option Explicit up there and make sure that you fully qualify everything. To instantiate your application, you use the Windows CreateObject function. CreateObject is cool because it will start SolidWorks only if it’s not already open. If it is open, it will latch onto the open process. Once you have the SolidWorks application object, you need the second component, which is the SolidWorks ModelDoc2 object. You have some functionality within the application, like the ability to open a file, but the majority of the functionality lies in the ModelDoc2 object and its children.
  • A quick plea for you here to please, please use good style when you’re programming. Comments will make your life infinitely easier when troubleshooting and debugging and will make it easier for those after you to maintain the code so they won’t call you when you’re on vacation or in the middle of an important presentation. Anticipate what bonehead issues your users will cause and what could possibly go wrong with your interactions with SolidWorks. When it comes to automation, SolidWorks is not all that forgiving. So test what’s going in and what’s going out to make sure that it’s what it’s supposed to be. Avoid those division by zero and type mismatch problems. Data types are especially critical with Excel because it likes to decide what data type things should be. And to simplify debugging, you can use a debug library (I’m sure there are some available on Google) or use the DEBUG tools within VBA to help log what’s going on.
  • OK, so once we have, with good style, a SolidWorks app and a SolidWorks ModelDoc2 object, then we can start passing information to SolidWorks. Another disclaimer here…in the interest of being able to fit things on the slides, I did NOT put any error trapping or testing in here. You definitely want to test your SolidWorks application object to make sure that it’s there. Check your ModelDoc2 object to make sure that it exists, and check your ModelDoc2 object to make sure that it is the correct type. ModelDoc2 supports parts, assemblies and drawings.To drive parameter values in SolidWorks, the syntax is quite simple. Your ModelDoc2 object has a Parameter property and you just assign a value to it. Since that property includes the name of the parameter, it’s very important to name your SolidWorks dimensions and features within the model. It’s also important not to CHANGE those names once your code is written. The same goes with your Excel. You can see that we’re using the syntax RANGE(“cellname”).VALUE. Simply naming the cell makes life sooooo much easier…no sheetnames no column numbers, no activating anything.Another thing to remember is that the SolidWorks API works in meters, and so must you. You can do that by easily multiplying or dividing by a factor. I, personally, think that’s very sloppy. I don’t like numbers in my equations unless they’re absolutely necessary. A better option is to build a quick function that converts inches into meters. One input and one output. If you want to go one step further, you can make the units in the UI in-cell pulldowns and then create a single function where you pass the value, the original units and the target units. It’s only going to be a couple of lines of code, but it will be very useful.You may also want to take advantage of some of the SolidWorks functionality to make this process easier. If you have five dimensions that are always going to be the same value, use a LINK VALUES, then drive one. Geometric relations like symmetry and midpoints are great ways to reduce your inputs. You can also use SolidWorks equations, but I greatly prefer link values over equations for equalities and I tend to put equations inside the automation. If there is a possibility that you may need to output or use the ending value in another calculation, put the equation in the automation.
  • OK, so once we have, with good style, a SolidWorks app and a SolidWorks ModelDoc2 object, then we can start passing information to SolidWorks. Another disclaimer here…in the interest of being able to fit things on the slides, I did NOT put any error trapping or testing in here. You definitely want to test your SolidWorks application object to make sure that it’s there. Check your ModelDoc2 object to make sure that it exists, and check your ModelDoc2 object to make sure that it is the correct type. ModelDoc2 supports parts, assemblies and drawings.To drive parameter values in SolidWorks, the syntax is quite simple. Your ModelDoc2 object has a Parameter property and you just assign a value to it. Since that property includes the name of the parameter, it’s very important to name your SolidWorks dimensions and features within the model. It’s also important not to CHANGE those names once your code is written. The same goes with your Excel. You can see that we’re using the syntax RANGE(“cellname”).VALUE. Simply naming the cell makes life sooooo much easier…no sheetnames no column numbers, no activating anything.Another thing to remember is that the SolidWorks API works in meters, and so must you. You can do that by easily multiplying or dividing by a factor. I, personally, think that’s very sloppy. I don’t like numbers in my equations unless they’re absolutely necessary. A better option is to build a quick function that converts inches into meters. One input and one output. If you want to go one step further, you can make the units in the UI in-cell pulldowns and then create a single function where you pass the value, the original units and the target units. It’s only going to be a couple of lines of code, but it will be very useful.You may also want to take advantage of some of the SolidWorks functionality to make this process easier. If you have five dimensions that are always going to be the same value, use a LINK VALUES, then drive one. Geometric relations like symmetry and midpoints are great ways to reduce your inputs. You can also use SolidWorks equations, but I greatly prefer link values over equations for equalities and I tend to put equations inside the automation. If there is a possibility that you may need to output or use the ending value in another calculation, put the equation in the automation.
  • And now it’s time for your first “Sherpa Tip”…
  • I can’t really stress the simplification idea enough. It amazes me that the same people that would walk into a test in college saying, “I only need a 74 to pass, that’s all I’m going to do” are the same people that spend 49 hours building a 78MB part that is purchased and that we only need to know the location of four bolt holes on. I can guarantee you that no matter how fast your automation runs, people will eventually complain about how slow it is. If your models are overly complex, it’s going to get exponentially slower.
  • In a lot of cases, you don’t even need Solid Geometry. Yes, it’s sexy looking, but guess what. This is automated. Nobody’s going to see it.
  • Simplification actually goes one step further when it comes to automation. Let me flash back to our opening and mention again that we are primarily talking here about design automation, that is, using SolidWorks to take a design that is somewhat repetitive in its nature, and allow many or even infinite combinations and permutations to be created of that design. We are NOT talking here about the occasional macro to save you four mouse clicks. So, in that vein, it is very important that when you look into automating your designs with the SolidWorks API, that you minimize, if not completely eliminate, any code that creates geometry. That is how the solution partners do it. They don’t build geometry. You build flexible, parametric geometry and their products manipulate it and, maybe assemble it. There are far too many things that can and will go wrong if you try to create your geometry through the API. That is not the best way to do automation. Here is a nice way to use it…
  • Here’s our scissor lift model. It’s actually made up of 4 sketches. I threw that cylinder in there for the visualization purposes of this slide only. Same with the planes. They don’t server any purpose except a visual aide for this image. We have a sketch with a single line that represents the overall length of the cylinder. We’re going to drive the length of that line to simulate the two extremes of the scissor lift. Then there are three separate sketches that are actually sitting on top of each other. The first sketch has two crossing lines representing a scissor lift with one…one sciss. We then have a two sciss sketch and a three sciss sketch. This allows us to put in separate height values for the sketches and to solve each possible case for the link length. So in essence, we’re running three case studies at once. We’ll drive the sketches, then have SolidWorks report back the leg lengths if we were to use one sciss, what the leg length would be if we used two scisses and also the answer if we used three. We’ll then use the automation tool to pick the best option.A quick note here is that the Link Length dimensions are sketch dimensions that have been created, named, then set to DRIVEN…in that order. If you create reference dimensions outside of a sketch, or inside of a sketch, you do not have the ability to rename them. For this reason, I highly recommend that you create dimensions that will overdefine your assembly in most cases. Leave them as driving in the warning dialog, rename them, then mark them as driven. Your sketch will be happy once more and you will have intelligently named reference dimensions.
  • Once we’ve driven the values that we need to drive, it’s time to rebuild the model. SolidWorks will often rebuild for us when we’re using it through the interface. Not so through the API. You need to tell SolidWorks when to rebuild. And to make matters worse, there are three ways to do it. You can see them up here. For our purposes, there are really two. EditRebuild is like hitting that traffic light with two lights. SolidWorks rebuilds what it thinks it needs to rebuild. Of course that dirty flag is notoriously unreliable, which is why we recommend the API equivalent of the Ctrl-Q. If you have a good size assembly, you can pass it TRUE to only rebuild the assembly and not the stuff underneath, but I certainly recommend doing the whole shebang.But here’s the thing…SolidWorks is always going to be the slowest part of this chain. So if you’re interested in performance, you may want to minimize the number of rebuilds that you have. Make as many changes as you can before you rebuild. You always need to rebuild before you retrieve any values, but most inputs can be made without a rebuild. Notable exceptions occur, of course, when one change modifies a feature that then needs to be acted on in such a way that faces or parameters won’t exist until the model is rebuilt. You’ll know when this happens when your numbers start coming out wrong and your code crashes.
  • So once we’ve rebuilt and SolidWorks has recalculated whatever it is that we want SolidWorks to calculate (our link lengths in this case), then we can retrieve the values. Retrieving parameter values is as simple as flipping the assignment equations around. Again, watch your data types and units. Dimensions will come back as doubles in meters, regardless of the units in your model. Once more, you can put the factor in there, or create some handy function to help you bring it over.You can bring these values into variables in your code, or straight into your design automation system (Excel cells in this case) and then use these values to perform more calculations. I know that I said that I wouldn’t do this, but let me actually show you one little bit of live code.
  • OK. I get the message. No live code. Just let me reboot. This will just take a second.
  • OK, I don’t think that we need Safe Mode.
  • We just need to wait a moment here while Vista boots.
  • So once we’ve rebuilt and SolidWorks has recalculated whatever it is that we want SolidWorks to calculate (our link lengths in this case), then we can retrieve the values. Retrieving parameter values is as simple as flipping the assignment equations around. Again, watch your data types and units. Dimensions will come back as doubles in meters, regardless of the units in your model. Once more, you can put the factor in there, or create some handy function to help you bring it over.You can bring these values into variables in your code, or straight into your design automation system (Excel cells in this case) and then use these values to perform more calculations. I know that I said that I wouldn’t do this, but let me actually show you one little bit of live code.
  • So once we have our values back from SolidWorks, We can go ahead and do more calculations. The calculations can exist either in your code or in your automation system. So this begs the question, where do I do the calcs? The deciding factor should be the type of calculation. If it’s something that Excel or your design automation can handle, do it there. The calculations are more visible; easier for non-programmers to maintain, update, or troubleshoot; and it allows you to store more engineering intelligence in your automation system, rather than in the code. Obviously, if it’s something that your design automation system can not handle, like some iterative algorithms, or if it involves going back to SolidWorks then it may be better to do it in the code.
  • As I said before, SolidWorks is going to be the slowest portion of the system. So just as we want to minimize the number of rebuilds, we certainly want to minimize the number of times we need to go back and forth with SolidWorks. If you are doing an iterative solving problem with SolidWorks, use intelligent seed values. Don’t just guess wildly, track the values that you’ve already used and how far off they were. Then interpolate or extrapolate to get a better seed value. And build a little intelligence into your first guess. If you were doing this by hand, you know you would mumble something like, “Well, if that’s 50 and that’s ¼, then it would be somewhere around 28…plus three quarters…carry the two…ok.” Put that same thought process into your automation to get good intelligent values.You can also build more intelligence into your models to minimize the amount of times that you have to drive SolidWorks. Use relationships between sketches, between parts. Use equations. Put multiple solutions in the model, like we did, and run them simultaneously.
  • OK, it’s time for your second “Sherpa Tip”. And I apologize for the quality of the video, the high altitude can really mess with the equipment and it’s hard to hold a camera still in 40 below temperatures with mittens on.
  • In most cases, the desired outputs of your automation will be the SolidWorks models and/or drawings. In other cases, you may want things like quotes, calculation documentation, inspection sheets, costing breakdowns, Bills of Materials, and so on. Most commercially available design automation solutions provide mechanisms to get you there. If you’re not using a commercially available product, or if they don’t support what you need, you can fairly easily put the stuff straight into your Excel spreadsheet or do any of these wonderful things in the code. And that’s the end of the process. Let’s look at another example…
  • OK, this example is actually based off of a true client story. The company name and the product have been radically changed to protect the intellectual property of the client. Have you ever seen how some urban buildings will have these spike strips to…um…discourage pigeons to land there and rain their wares upon unsuspecting folks below? Well out in the suburbs, I figured we need the same thing for those pesky suburban rats that drain your bird feeders. So I invented the Specialized Squirrel Skewer Syndicate. A company dedicated to protecting the food supply for our suburban avian friends. Just put these specially designed speed bump skewers around your feeders and you’re set. Small birds can land on them and grip onto the side as if it were a pond reed, but the bushy tail rodents will be kept out. And the company actually custom designs skewers for each application. Based on the width and length of the railing as well as the particular size of your unwelcome inhabitants, the curvature and shape of the plastic base are modified along with the spacing and angle of the metal enforcement devices to provide optimum protection against invasions of Sciuruscarolinensis.
  • So the design approach here is to take the inputs that we mentioned, and drive the base geometry. But to determine the spike placement, we need to ensure that the minimum and maximum distance between the spikes falls within a tolerance zone that we have determined through years of empirical experimentation. So we will determine a first pass number, drive the shape of the base part, then drive the locations of the points on the base part and the angles of the mates in the assembly. Then we’ll rebuild the model and do a measure finding the minimum and maximum distances between the two parts in the assembly, pass those back to our design automation and determine if they are within tolerance. If they are, then we can go ahead and finalize the design in our automation system. If not, we recalculate the spacings and angles, drive the SolidWorks model again, retrieve new values and continue to iterate.
  • So here is the model that we have. It’s a simplified model made up of a single swept feature for the plastic base. Then we took two sketches and extruded them up into surfaces. We then added two planes offset along the depth of the base. The spikes are always going to lie at the intersection of these three entities: The sweep, the projected sketch and the plane. We then made a simple assembly by inserting two very simple spike components. We put some datum point features on the tips of the spikes to make it easier to measure. Our goal is to drive the shape of the base part and depth of the planes to determine the locations of the spikes.
  • Programmatically, this is what we did. We developed an empirical equation to determine the spacing for the two planes. It was a simple geometric equation assuming that everything is square and flat, and factoring in some tests that we did to come up with some constants. That equation takes the inputs and ballparks the plane distances. We then push those and the dimensions for the sweep into SolidWorks. We regenerate the model which relocates the planes, then the intersection point, which drives the location and mating conditions for the spikes. We then measure the min and max distances between the spikes and pass them from SolidWorks back to our automation. We look at those distances and see if they’re within a tolerance percentage of the dimensions of the squirrel. If they are, then we’re off to the races and we pass the values to the correct Excel cells. If the numbers are outside of tolerance, we see which direction and how far, then we adjust and repeat the SolidWorks loop until they are within tolerance.
  • Sounds simple enough, right? Well, here’s how we tackled the tricky bits. We took operations that we would potentially do more than once and we made separate functions for them. This does save some time in coding, but the best advantage of doing this is that it really simplifies your code. Imagine a flowchart, with each rectangle in it another calculation. With the use of functions, your main code will look just like that. And each calculation will be its own separate code task.
  • When you sit down to write the code, I can guarantee that you’re not going to think that you need all of this. But quite often to get to what you need in SolidWorks you need to understand the SolidWorks object structure. I don’t want to spend too much time explaining OOP, since it is covered in last year’s presentation available at www.razorleaf.com, but when it comes to SolidWorks, each object type has its own properties and methods. And what is quite unfortunate is that there are a lot of objects. They get fairly specific. And what you need to do is quite often not available for the object that you have. As a result, you spend an inordinate amount of time going up and down the object structure looking for the object that you need.
  • Case in point. I want a distance. That distance is created running the calculate method on a measure object. So that means that I need to get the measure object. I also need to specify what I’m calculating. That can be the selection set, at which point you would need to select things and have a selection manager object to manage them. Here we went the other route and we’re passing it an array of objects. So we have to create the array, and we need to populate the array with the two faces that we’re measuring between. To get the face objects, we need the body object. To get the body object, we need the component object or the part object. To get the component object, we need to cycle through an array of components that we get from the assembly object which we get from the ModelDoc2 object which we ultimately get from the SolidWorks Application object.Now I know what you’re thinking. That’s a lot of work, there’s got to be an easier way. If you find it, let me know. And before you say anything, simply selecting the face by its name does not work. You think that it would, but in our testing it just wouldn’t work. But the theory is this. Start with the end in mind, as Stephen Covey would say. Understand your overall design and what you’re after. Then figure out what you need to get that, then what you need to get that, then what you need to get that…and so on. That’s one reason that I loved the old API guide. You could select an object and look at its ACCESSORS, that is, what methods are available for you to get that object. Quite handy.
  • So that leads us to our third and final “Sherpa Tip”
  • So what if you want to do more than modify a parameter value? Well, we gave you the secret a minute ago. The basic approach is to figure out where the property that you want to change or method that you want to act upon is located in the object model. Then figure out how to get there. Sometimes you can use the Selection Manager and sometimes you can get lucky to get SelectByID2 to work. In a lot of cases, though, you end up traversing the tree. Getting the right objects (or Interfaces if you’re in .NET) is probably 85% of the fight in SolidWorks programming.
  • Other things that you may want to do include mass properties. There is an object for that. Section properties, there’s actually no object for this, but instead, it returns a SafeArray. SolidWorks used to use these a lot, but their popularity is waning. In essence, if there are multiple values, SolidWorks will throw them all into a giant array of values. What’s difficult about that is that you need to know which entity in the array you’re looking for. Somewhat clumsy, but that’s life. Sheesh. I can’t even get away from these pop-up ads in a PowerPoint!! NO! I do NOT want to take a survey, because I am not a satisfied customer!
  • We already saw the measure object (Imeasure interface in .NET) at work a little. Here’s is the deal with the measure object. First, you must create the object. You can set some properties on it, like precision and units and how arcs are measured. Then you kick off the CALCULATE method. Here you pass it an array of objects. If you pass it NOTHING, then it measures the current selection set. Be sure to use the SelectionManager object to manage this. If you choose to build your own object array, you can do that fairly easily as well, like we did in the last example. Once you calculate, you can then grab whatever values you want from the object’s properties.
  • Here’s another nifty one. Macro features. I won’t go into depth on how to create these, it’s pretty well documented. The idea, though, is that you have a SolidWorks Macro and you stick it at a specific spot IN the Feature Mangler. SolidWorks will then execute that code every time that it hits that point in the Feature Mangler. Here are some great uses for it. Primarily they center around looking at the model in an unfinished state, taking some information from there and passing it back to the automation or using that to continue the construction of the model. If you think about the SolidWorks model as mimicking your manufacturing process, then the macro feature allows you to report back information while your part is sitting, queued up for the next process. Handy little feature.
  • OK, I’ve mentioned .NET a little here and there. And you are certainly welcome to use .NET if you want. Is it a better programming language? No question. Is it necessary? Not in most cases. One thing that I can’t stress enough is that while we have talked primarily about programming here today, the code is designed to augment your design automation. I DO NOT recommend a custom programmed solution (although Razorleaf Corporation will be happy to write one for you if you insist). Go to the Partner Pavilion and see what’s there for design automation. The best benefit of design automation is to capture and document your intellectual property. The hows and whys of your design. Programming languages are a lousy medium for doing that.
  • Once again, here are the steps.
  • So here are the highlights. We’re talking about using SolidWorks to perform complex calculations. We do that by collecting information in our design automation system,

SolidWorks Design Automation Using the SolidWorks API, Microsoft Excel and VBA SolidWorks Design Automation Using the SolidWorks API, Microsoft Excel and VBA Presentation Transcript

  • Managing Fiduciary Responsibility Within a Keynesian Economic Environment A New View of Investments in a Post- Crisis Capital Downturn World September 15, 2009 Paul Gimbel Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • Design Automation: Simple SolidWorks Solutions to Practical Programmatic Packages Part 2: Programmatic Automation Using SolidWorks for Computations September 15, 2009 Paul Gimbel Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • If You Use This… Copyright © 2009 Razorleaf Corporation www.razorleaf.com View slide
  • Or This… Copyright © 2009 Razorleaf Corporation www.razorleaf.com View slide
  • Or One of These… Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • Or This… Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • Or This… Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • Or Even This… Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • Then you need… Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • Design Automation: Simple SolidWorks Solutions to Practical Programmatic Packages Part 2: Programmatic Automation Using SolidWorks for Computations September 15, 2009 Paul Gimbel Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • And a Very Expensive Calculator at That SolidWorks: The Ultimate Calculator for Design Automation Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • “Thinking…Bad. SolidWorks…Good.” Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • Engineering Education Skills • • Beer Pong • Penny Locks • Mountain Dew + Espresso Beans • Creative Culinary Techniques Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • Types of Interaction • People use Automation to: • Produce SolidWorks Models/Drawings • Guide Users to Ensure Good Input • Feasibility or Performance Calculations • Predicted Performance • Shipping Weight • Cost Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • Applications • Complex Geometric Calculations • Manufacturability • Interference/Clearance • Simultaneous Equations • Design Validation • Top-Down Assembly Modeling Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • Examples: Complex Geometric Calculations • Linkage • Truss • Belt & Pulley System Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • Examples: Manufacturability • Complex Sheet Metal • Tooling Decisions • Assembly and Tool Clearance • Tolerancing Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • Examples: Interference/Clearance • Complex Fit Problems • Iterative Optimization • Validation Checks • Clearance Value Determination Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • Examples: Simultaneous Equations • Equations Tying Sketches Together • Circular Problems • Mixed Arithmetic and Geometric “Equations” Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • Examples: Design Validation • Form, Fit, and Function • Geometric Impossibilities • Weight Problems • Return Values for Performance Calculations Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • Examples: Top-Down Assembly Modeling (TDAM) • Enclosures • Intersecting Surfaces • Matched Components Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • Before We Start Talking Code… • Microsoft Excel Samples • Yes, Excel. Here‟s why: • Excel does a lot of the work • VisualStudio.NET is expensive • You spent all your budget coming here • Familiar/Friendly user interfaces • It demo’s well • If you think my jokes are bad, you should see my C# code Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • Nope. Not Going To Do It • NO LIVE CODE TODAY!! • I’ve seen enough of these things to know • Too slow (and boooooooring) • You don’t want to watch me search for typos • MY code won’t crash…GUARANTEED • Full code will be available upon request • Supported by PETA (People for the Ethical Treatment of Audiences) Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • Sample 1: The Simple Out-And- Back • Southern States Superior Spring and Scissor Lift Systems • Input required height • Input max weight • Return linkage lengths • Return output points • Run stress calculation • Iterate as needed • Output data sheet Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • Design Automation Steps 1.Collect inputs 2.Perform arithmetic and logic calculations 3.Attach to SolidWorks 4.Pass values to SolidWorks 5.Force regeneration of model 6.Retrieve values from SolidWorks 7.Perform further calculations 8.Iterate with SolidWorks as needed 9.Generate outputs Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • 1) Collect Inputs NAME THESE INPUT CELLS Type Cell Name Here Check out SWW2008 NAME THESE presentation…”Automating Your OUTPUT CELLS Designs: Excel, VBA, and Beyond” at www.razorleaf.com for tips on using Excel for design automation Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • 2) Perform Arithmetic and Logic Calculations • Convert the units as needed • Determine the smallest cylinder that will support the load • Determine stroke for selected cylinder Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • 3) Attach to SolidWorks • Check your references • Be specific with your data types • Use CreateObject • Attach/Create new SolidWorks • Open your master file Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • 3) Attach to SolidWorks Option Explicit Sub CalculateScissor() „Results variables for SolidWorks to return Dim bStatus As Boolean Dim lStatus As Long Dim lWarnings As Long Dim swApp As SldWorks.SldWorks „Object holding the SolidWorks Session „Attach to or create a SolidWorks Session Set swApp = CreateObject(“SolidWorks.Application”) Dim swPart As SldWorks.ModelDoc2 „Object holding our SolidWorks document „Open our part swApp.OpenDoc6 “C:SSSSSLiftScissorLift.Sldprt”, 1, 0, “”, lStatus, lWarnings Set swPart = swApp.ActivateDoc2(“ScissorLift.Sldprt”, False, lStatus) Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • Public Service Announcement • Proper Programming Style includes: • „Commenting the snot out of everything • Error trapping (On Error Goto/Try…Catch) • Testing for data types (important when interacting with Excel) • Testing for objects (If myObject IS NOTHING Then panic) • Including Debug Code (Debug.Print/Assert, or a log file if you’re lucky enough to have a debug library) Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • 4) Pass Values to SolidWorks • Name your features and dimensions in SolidWorks • If you need to select, avoid “screen picks” • Travel up and down the object tree • SolidWorks tools to make inputs easier • Link Values • Geometric Relations (ex. Symmetry) • Equations Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • 4) Pass Values to SolidWorks swPart.Parameter(“OverallLength@BaseLine@ScissorLift.Part"). SystemValue = Range(“StrokeInches”).Value * 0.0254 ...or better yet... = InchesToMeters(Range("StrokeInches").Value) ...or even better yet... = Convert(Range("Stroke").Value, Range("SUnits").Value, "meters") Must be in meters NOTE: When getting or setting values from Excel, name the cells and use Range(”name”).value Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • Simplify Your Life (By Simplifying Your Models) •Sherpa Tip #1 Sherpa #1 Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • Simplified Models and Automation • Why are you building a model? • Visualization? • Model is so it LOOKS right • Simulation? • Model it so it WORKS right • Calculation? • Model it so it gives you the right result • Drawings? • Model it so that the drawings are correct • To win that SolidWorks model contest? • OK, fine. Go for it. Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • Did I Say Simple? Oh yeah. Simple. • Do you need threads? • Do you need swoopies? • Do you need fillets? • Do you need hardware? • Do you need mounting holes? • Do you need SOLID GEOMETRY? Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • Don‟t Invent the Wheel, Redesign It Drive Geometry …Don’t create it If the world was indeed created in six days, I bet it wasn’t through the SolidWorks API Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • Scissor Lift Model Retracted Each stack is a separate sketch Plane Extended Plane Stroke Drive to set height goal Just for show: completely unnecessary Single line is the real sketch Drive to change the geometry Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • 5) Force Regeneration of Model • SolidWorks has three different rebuild methods: • swPart.Rebuild (Assemblies and Drawings only) • swPart.EditRebuild3 (Rebuilds only what “needs” to be rebuilt) • swPart.ForceRebuild3 (Rebuilds everything with a “Top Only” option) “Sherpa Recommended!!” • You also have an option to suppress error messages…use it! • swPart.ShowFeatureErrorDialog = FALSE • Don‟t rebuild unless you need to, but keep in mind… • Any time that you need to retrieve values, rebuild first • Some changes require, or are better off, after a rebuild • Ex. Referencing an entity created/modified in earlier step Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • 6) Retrieve Values from SolidWorks • Populate Excel cells, instead of just bringing values into VBA variables • Provides greater visibility to calculations • Easier to troubleshoot • Allows you to use Excel for validations and further calculations • Give Management their graphs and charts • Use the same syntax as driving values…only backwards Watch your units and data types Let’s see the code! Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • 6) Retrieve Values from SolidWorks Range(“LinkLength”).Value = Part.Parameter(“LinkLength@Links3@ScissorLift.Part"). SystemValue / 0.0254 ...or better yet... = MetersToInches(Part.Parameter (“LinkLength@Links3@ScissorLift.Part").SystemValue ) ...or even better yet... = Convert(Part.Parameter(“LinkLength@Links3@ScissorLift.Part"). SystemValue , "meters“, Range("SUnits").Value) Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • 7) Perform Further Calculations Perform code calculations if: • you still need interact with SolidWorks • you’re dealing with data that Excel doesn’t handle well (arrays) • you need to loop Perform calculations in your DA System if: • you are done with SolidWorks • you want visibility into your calculations • you don’t want me to yell at you and deduct 15 style points Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • 8) Iterate with SolidWorks as Needed Minimize your round trips to SolidWorks by: • Analyzing your outputs • Performing calculations to get more accurate seed values • Design your models to minimize rebuilds and leverage relations/equations Keep the SolidWorks object so there‟s no need to reinstantiate Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • You ARE the Brute Squad! •Sherpa Tip #2 Sherpa #2 Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • 9) Generate Outputs Quite often you can simply: • Use the outputs from your design automation tool • Format results in Excel or Word In other cases, you can: • Drive custom property value (for SolidWorks drawings, BOM, Word docs) • Write to text files • Send information to databases Can‟t afford Microsoft SQLServer? Check out SQLExpress. with 80% of the functionality and 0g Trans Fat at 0% of the cost!! http://www.microsoft.com/Sqlserver/2005/en/us/express.aspx Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • Sample 2: Locating By Clearance Specialized Squirrel Skewer Syndicate • Spikes must be within a tolerance depending on rodent girth • Base plastic strip is complex shape • Inputs include railing width and length and the target size of the source of the client’s ire Sciurus Carolinensis *Based VERY loosely on a true client story! Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • Squirrel Skewering Approach Inputs: • Base Geometric Requirements • Railing Width • Railing Length • Rodent Size • Generate Simplified model with Spike#1 • Guess where Spike #2 should go • Measure clearance • If clearance is within tolerance, return location • If clearance is outside of tolerance, iterate No squirrels or SolidWorks models were harmed in the making of this presentation Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • The Model Five Simple Features: 1. A swept feature to represent the plastic base 2. A sketch representing the profile 3. A cylinder representing one spike 4. A cylinder representing the other spike 5. Datum points on the tips 6. A few mates Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • The Program Flow • Before the code is launched: • Users enter Profile Radius, Profile Length, Spike Spacing, Tolerance • The code then: Push Guess Regenerate Measure Fill Values Values to Spacing Model Clearance Into Excel SW YES Is Clearance NO Within Tolerance? Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • Coding the Tricky Bits: Guessing The Seed Value • Always send an intelligent starting value • Minimize the number of trips you need to make • Track your values for trending • Create an array of the values • Use an interpolation/extrapolation routine to determine next seed Public Function Seed(SeedValues() as Double, _ LastResult As Double, Goal As Double, _ Tolerance As Double)As Double Seed will look at the result to see if it was too high or too low, Find the next seed value in that direction (if there is one), and interpolate based on how far out of tolerance (in %) it was Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • Coding the Tricky Bits: Measuring Clearance Values • Just a few of the Variables: • Dim swApp As SldWorks.SldWorks • Dim swDoc As SldWorks.ModelDoc2 • Dim swAssy As SldWorks.AssemblyDoc • Dim swComps As Variant „Array of components • Dim swFaces() As SldWorks.Face2 • Dim swComp As SldWorks.Component2 • Dim swBody As SldWorks.Body2 • Dim swFace As SldWorks.Face2 • Dim swMeasure As SldWorks.Measure • Dim Distance As Double Check out last year’s presentation…”Automating Your Designs: Excel, VBA, and Beyond” at www.razorleaf.com for tips on OOPs in SolidWorks and Excel (I know it’s not TRUE OOP. So if you’re a coder, don’t bother yelling at me…I know.) Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • Follow the Bouncing Objects Sub main() Set swApp = CreateObject(“SolidWorks.Application”) Set swDoc = swApp.ActiveDoc Set swAssy = swDoc **Lots of loops, swComps = swAssy.GetComponents(True) comments, error Set swComp = swComps(index) trapping, and other Set swBody = swComp.GetBody stuff left out for Set swFace = swBody.GetFirstFace clarity** Set swFaces(FaceCount) = swFace Set swMeasure = swDoc.Extension.CreateMeasure bResult = swMeasure.Calculate(swFaces) Distance = swMeasure.Distance The Takeaway: Work TOP DOWN! Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • Work Top Down (unless you design skyscrapers) •Sherpa Tip Sherpa #3 #3 Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • Controlling Features and Other Friends Modifying most SolidWorks content involves selection… • Set swSelMgr = swModel.SelectionManager • Set swFeat = swSelMgr.GetSelectedObject5(1) or • Set swFeat = swEditAssy.FeatureByName(sFeatName) • bResult = swFeat.Select2(False, 0) • bResult = swPart.EditSuppress2() …or traversing the object tree • Set swApp = CreateObject(“Application.SldWorks”) • Set swModel = swApp.ActiveDoc • Set swModelExt = swModel.Extension… • swAnnViews = swModelExt.AnnotationViews… • Set swAnnView = swAnnViews(i)… • swAnnotations = swAnnView.Annotations… • Set swAnn = swAnnotations(j)…and so on… Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • Other Calculations from SolidWorks Mass Properties Dim swMass As SldWorks.MassProperty Set swMass = swPart.Extension.CreateMassProperty Access properties swMass.mass or .Volume or .SurfaceArea… Section Properties Dim swPart As Sldworks.ModelDoc2 Dim swPartDocExt as Sldworks.ModelDocExtension Dim vFace As Variant Dim vSecProps as Variant Set swPart = swApp.ActiveDoc Set swPartDocExt = swPart.Extension „Get face through selection or traverse Body->Face… vSecProps = swPartDocExt.GetSectionProperties2((vFace)) Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • Measure: An Object Unto Itself There is a Measure object (Imeasure Interface) with its own properties Dim Measurement as SldWorks.Measure Dim bResult as Boolean Dim dResult as Double Build your selection set using SelectByID, etc. Set Measure = swPart.Extension.CreateMeasure Measure.ArcOption = 0 „Center-to-Center/Min/Max bResult = Measure.Calculate(Nothing) You can also calculate an array of objects Dim swObjects() As Variant swObjects(0) = swFace „Previously captured object swObjects(1) = swPoint „Previously captured object bResult = Measure.Calculate(swObjects) Then grab the property of the measure that you‟re after dResult = Measure.Length (or .Radius or .Angle or .Area or…) Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • Macro Features Use macro features to execute: • On each rebuild • Report values back to your automation, file, or database • At a specific point during the rebuild • Perform “calculations” at particular manufacturing step • Report values back to the design automation • Get results to use further down the tree • Use mass properties values to drive additional features • Interruptions • Add flow, logic and validation to your SolidWorks models • Head off problems before SolidWorks fails or wastes time Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • SolidWorks and .NET From a SolidWorks API functionality perspective there is no difference between VBA and .NET Consider .NET if you: • Have no need for a user interface (Excel does that well) • Want to protect your code and app (Compiled code versus exposed) • Have a lot of redundancies (Inheritance) • Complex algorithms (Polymorphism) • Need more structure in your life (True OOP) • Are all about efficiency and are a seasoned coder Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • Design Automation Steps 1.Collect inputs 2.Perform arithmetic and logic calculations 3.Attach to SolidWorks 4.Pass values to SolidWorks 5.Force regeneration of model 6.Retrieve values from SolidWorks 7.Perform further calculations 8.Iterate with SolidWorks as needed 9.Generate outputs Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • Concluding Tips and Techniques • Perform calculations BEFORE you get to SolidWorks • SolidWorks will be the slowest link in the chain • Simplify your geometry • Avoid creating geometry on the fly • Kickoff SolidWorks, don’t let it decide when it will generate • Brute Force is not necessarily a bad thing (ESPECIALLY when it’s SolidWorks exerting the force) • Work Top-Down…start with the end in mind Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  • Thank You! (for staying awake…well most of you at least) • If you have questions, feel free to call me at home ▫ My name is Mickey Dorsey, (302)… • Feel free to grab me (or my card) after the show Paul Gimbel Business Process Sherpa paul.gimbel@razorleaf.com www.razorleaf.com For the complete version of the presentation, visit www.razorleaf.com after the show! Yes, it’s free. Sign up for our FREE eNewsletter, too (news, tech tips, and more). Copyright © 2009 Razorleaf Corporation www.razorleaf.com