Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

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

17,321 views

Published on

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

Published in: Technology, Business
  • Be the first to comment

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

  1. 1. 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
  2. 2. 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
  3. 3. If You Use This… Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  4. 4. Or This… Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  5. 5. Or One of These… Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  6. 6. Or This… Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  7. 7. Or This… Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  8. 8. Or Even This… Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  9. 9. Then you need… Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  10. 10. 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
  11. 11. And a Very Expensive Calculator at That SolidWorks: The Ultimate Calculator for Design Automation Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  12. 12. “Thinking…Bad. SolidWorks…Good.” Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  13. 13. Engineering Education Skills • • Beer Pong • Penny Locks • Mountain Dew + Espresso Beans • Creative Culinary Techniques Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  14. 14. 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
  15. 15. Applications • Complex Geometric Calculations • Manufacturability • Interference/Clearance • Simultaneous Equations • Design Validation • Top-Down Assembly Modeling Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  16. 16. Examples: Complex Geometric Calculations • Linkage • Truss • Belt & Pulley System Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  17. 17. Examples: Manufacturability • Complex Sheet Metal • Tooling Decisions • Assembly and Tool Clearance • Tolerancing Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  18. 18. Examples: Interference/Clearance • Complex Fit Problems • Iterative Optimization • Validation Checks • Clearance Value Determination Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  19. 19. Examples: Simultaneous Equations • Equations Tying Sketches Together • Circular Problems • Mixed Arithmetic and Geometric “Equations” Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  20. 20. Examples: Design Validation • Form, Fit, and Function • Geometric Impossibilities • Weight Problems • Return Values for Performance Calculations Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  21. 21. Examples: Top-Down Assembly Modeling (TDAM) • Enclosures • Intersecting Surfaces • Matched Components Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  22. 22. 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
  23. 23. 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
  24. 24. 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
  25. 25. 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
  26. 26. 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
  27. 27. 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
  28. 28. 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
  29. 29. 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
  30. 30. 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
  31. 31. 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
  32. 32. 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
  33. 33. Simplify Your Life (By Simplifying Your Models) •Sherpa Tip #1 Sherpa #1 Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  34. 34. 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
  35. 35. 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
  36. 36. 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
  37. 37. 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
  38. 38. 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
  39. 39. 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
  40. 40. Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  41. 41. Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  42. 42. Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  43. 43. 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
  44. 44. 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
  45. 45. 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
  46. 46. You ARE the Brute Squad! •Sherpa Tip #2 Sherpa #2 Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  47. 47. 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
  48. 48. 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
  49. 49. 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
  50. 50. 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
  51. 51. 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
  52. 52. 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
  53. 53. 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
  54. 54. 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
  55. 55. Work Top Down (unless you design skyscrapers) •Sherpa Tip Sherpa #3 #3 Copyright © 2009 Razorleaf Corporation www.razorleaf.com
  56. 56. 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
  57. 57. 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
  58. 58. 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
  59. 59. 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
  60. 60. 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
  61. 61. 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
  62. 62. 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
  63. 63. 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

×