solidworks design automation using the solidworks api, microsoft excel and vba
DESCRIPTION
Design Automation Techniques (session 2) with SolidWorks 2009 and 2010, Excel and VBA - Presented to Greenville (SC) SolidWorks User Group September 15, 2009 @ CU-ICARTRANSCRIPT
Copyright © 2009 Razorleaf Corporation www.razorleaf.com
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
Or This…
Copyright © 2009 Razorleaf Corporation www.razorleaf.com
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
• Beer Pong
Engineering Education Skills
• Beer Pong
• Penny Locks
• Mountain Dew + Espresso Beans
• Creative Culinary Techniques
• Beer Pong
• Penny Locks
+=
• Beer Pong
• Penny Locks
• Mountain Dew + Espresso Beans
Copyright © 2009 Razorleaf Corporation www.razorleaf.com
•People use Automation to:• Produce SolidWorks Models/Drawings• Guide Users to Ensure Good Input• Feasibility or Performance Calculations
• Predicted Performance• Shipping Weight• Cost
Types of Interaction
Copyright © 2009 Razorleaf Corporation www.razorleaf.com
• Complex Geometric Calculations• Manufacturability• Interference/Clearance• Simultaneous Equations• Design Validation• Top-Down Assembly Modeling
Applications
Copyright © 2009 Razorleaf Corporation www.razorleaf.com
• Linkage• Truss• Belt & Pulley System
Examples: Complex Geometric Calculations
Copyright © 2009 Razorleaf Corporation www.razorleaf.com
• Complex Sheet Metal• Tooling Decisions• Assembly and Tool Clearance• Tolerancing
Examples: Manufacturability
Copyright © 2009 Razorleaf Corporation www.razorleaf.com
• Complex Fit Problems• Iterative Optimization• Validation Checks• Clearance Value Determination
Examples: Interference/Clearance
Copyright © 2009 Razorleaf Corporation www.razorleaf.com
• Equations Tying Sketches Together
• Circular Problems• Mixed Arithmetic and
Geometric “Equations”
Examples: Simultaneous Equations
Copyright © 2009 Razorleaf Corporation www.razorleaf.com
• Form, Fit, and Function• Geometric Impossibilities• Weight Problems• Return Values for Performance Calculations
Examples: Design Validation
Copyright © 2009 Razorleaf Corporation www.razorleaf.com
• Enclosures• Intersecting Surfaces• Matched Components
Examples: Top-Down Assembly Modeling (TDAM)
Copyright © 2009 Razorleaf Corporation www.razorleaf.com
• 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
Before We Start Talking Code…
Copyright © 2009 Razorleaf Corporation www.razorleaf.com
•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)
Nope. Not Going To Do It
Copyright © 2009 Razorleaf Corporation www.razorleaf.com
•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
Sample 1: The Simple Out-And-Back
Copyright © 2009 Razorleaf Corporation www.razorleaf.com
1.Collect inputs2.Perform arithmetic and logic calculations3.Attach to SolidWorks4.Pass values to SolidWorks5.Force regeneration of model6.Retrieve values from SolidWorks7.Perform further calculations8.Iterate with SolidWorks as needed9.Generate outputs
Design Automation Steps
Copyright © 2009 Razorleaf Corporation www.razorleaf.com
1) Collect Inputs
NAME THESE INPUT CELLS
NAME THESE OUTPUT CELLS
Type Cell Name Here
Check out SWW2008 presentation…”Automating Your
Designs: Excel, VBA, and Beyond” at www.razorleaf.com
for tips on using Excel for design automation
Copyright © 2009 Razorleaf Corporation www.razorleaf.com
• Convert the units as needed
• Determine the smallest cylinder that will support the load
• Determine stroke for selected cylinder
2) Perform Arithmetic and Logic Calculations
Copyright © 2009 Razorleaf Corporation www.razorleaf.com
• Check your references• Be specific with your data types• Use CreateObject
• Attach/Create new SolidWorks• Open your master file
3) Attach to SolidWorks
Copyright © 2009 Razorleaf Corporation www.razorleaf.com
3) Attach to SolidWorksOption ExplicitSub CalculateScissor()
‘Results variables for SolidWorks to returnDim bStatus As BooleanDim lStatus As LongDim lWarnings As Long
Dim swApp As SldWorks.SldWorks ‘Object holding the SolidWorks Session‘Attach to or create a SolidWorks SessionSet swApp = CreateObject(“SolidWorks.Application”)
Dim swPart As SldWorks.ModelDoc2 ‘Object holding our SolidWorks document‘Open our partswApp.OpenDoc6 “C:\SSSSSLift\ScissorLift.Sldprt”, 1, 0, “”, lStatus, lWarningsSet swPart = swApp.ActivateDoc2(“ScissorLift.Sldprt”, False, lStatus)
Copyright © 2009 Razorleaf Corporation www.razorleaf.com
•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)
Public Service Announcement
Copyright © 2009 Razorleaf Corporation www.razorleaf.com
• 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
4) Pass Values to SolidWorks
Copyright © 2009 Razorleaf Corporation www.razorleaf.com
4) Pass Values to SolidWorks
swPart.Parameter(“OverallLength@[email protected]").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")
NOTE: When getting or setting values from Excel, name the cells and use Range(”name”).value
Must be in meters
Copyright © 2009 Razorleaf Corporation www.razorleaf.com
•Sherpa Tip #1
Simplify Your Life (By Simplifying Your Models)
Sherpa Tip #1
Copyright © 2009 Razorleaf Corporation www.razorleaf.com
• 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.
Simplified Models and Automation
Copyright © 2009 Razorleaf Corporation www.razorleaf.com
•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?
Did I Say Simple? Oh yeah. Simple.
Copyright © 2009 Razorleaf Corporation www.razorleaf.com
Drive Geometry…Don’t create it
If the world was indeed created in six days, I bet it wasn’t through the SolidWorks API
Don’t Invent the Wheel, Redesign It
Copyright © 2009 Razorleaf Corporation www.razorleaf.com
Scissor Lift Model
Extended Plane
Retracted Plane
Drive to set height goal
Each stack is a separate sketch
Stroke
Drive to change the geometry
Just for show: completely unnecessarySingle line is the real sketch
Copyright © 2009 Razorleaf Corporation www.razorleaf.com
• 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
5) Force Regeneration of Model
Copyright © 2009 Razorleaf Corporation www.razorleaf.com
• 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!
6) Retrieve Values from SolidWorks
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@[email protected]").SystemValue / 0.0254 ...or better yet... = MetersToInches(Part.Parameter(“LinkLength@[email protected]").SystemValue ) ...or even better yet... = Convert(Part.Parameter(“LinkLength@[email protected]").SystemValue , "meters“, Range("SUnits").Value)
Copyright © 2009 Razorleaf Corporation www.razorleaf.com
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
7) Perform Further Calculations
Copyright © 2009 Razorleaf Corporation www.razorleaf.com
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
8) Iterate with SolidWorks as Needed
Copyright © 2009 Razorleaf Corporation www.razorleaf.com
Sherpa Tip #2
•Sherpa Tip #2
You ARE the Brute Squad!
Copyright © 2009 Razorleaf Corporation www.razorleaf.com
Quite often you can simply:• Use the outputs from your design automation tool• Format results in Excel or WordIn other cases, you can:• Drive custom property value (for SolidWorks drawings,
BOM, Word docs)• Write to text files• Send information to databases
9) Generate Outputs
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
• 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
Sample 2: Locating By Clearance
*Based VERY loosely on a
true client story!
Specialized Squirrel Skewer Syndicate
Sciurus Carolinensis
Copyright © 2009 Razorleaf Corporation www.razorleaf.com
Squirrel Skewering Approach
No squirrels or SolidWorks models were harmed in the making of this presentation
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
Copyright © 2009 Razorleaf Corporation www.razorleaf.com
Five Simple Features:1. A swept feature to represent the plastic base2. A sketch representing the profile3. A cylinder representing one spike4. A cylinder representing the other spike5. Datum points on the tips6. A few mates
The Model
Copyright © 2009 Razorleaf Corporation www.razorleaf.com
• Before the code is launched:• Users enter Profile Radius, Profile Length, Spike Spacing,
Tolerance• The code then:
The Program Flow
Guess Spacing
Push Values to
SW
Regenerate Model
Measure Clearance
Fill Values Into Excel
Is Clearance Within
Tolerance?NO
YES
Copyright © 2009 Razorleaf Corporation www.razorleaf.com
• 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
Coding the Tricky Bits: Guessing The Seed Value
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
•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
Coding the Tricky Bits: Measuring Clearance Values
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
Sub main()
Set swApp = CreateObject(“SolidWorks.Application”)Set swDoc = swApp.ActiveDocSet swAssy = swDocswComps = swAssy.GetComponents(True)Set swComp = swComps(index)Set swBody = swComp.GetBodySet swFace = swBody.GetFirstFaceSet swFaces(FaceCount) = swFaceSet swMeasure = swDoc.Extension.CreateMeasurebResult = swMeasure.Calculate(swFaces)Distance = swMeasure.Distance
Follow the Bouncing Objects
**Lots of loops, comments, error trapping, and other stuff left out for clarity**
The Takeaway: Work TOP DOWN!
Copyright © 2009 Razorleaf Corporation www.razorleaf.com
•Sherpa Tip #3
Work Top Down (unless you design skyscrapers)
Sherpa Tip #3
Copyright © 2009 Razorleaf Corporation www.razorleaf.com
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…
Controlling Features and Other Friends
Copyright © 2009 Razorleaf Corporation www.razorleaf.com
Mass PropertiesDim swMass As SldWorks.MassPropertySet swMass = swPart.Extension.CreateMassProperty
Access properties swMass.mass or .Volume or .SurfaceArea…
Section PropertiesDim swPart As Sldworks.ModelDoc2Dim swPartDocExt as Sldworks.ModelDocExtensionDim vFace As VariantDim vSecProps as VariantSet swPart = swApp.ActiveDocSet swPartDocExt = swPart.Extension‘Get face through selection or traverse Body->Face…vSecProps = swPartDocExt.GetSectionProperties2((vFace))
Other Calculations from SolidWorks
Copyright © 2009 Razorleaf Corporation www.razorleaf.com
There is a Measure object (Imeasure Interface) with its own propertiesDim Measurement as SldWorks.MeasureDim bResult as BooleanDim dResult as Double
Build your selection set using SelectByID, etc.Set Measure = swPart.Extension.CreateMeasureMeasure.ArcOption = 0 ‘Center-to-Center/Min/MaxbResult = Measure.Calculate(Nothing)
You can also calculate an array of objectsDim swObjects() As VariantswObjects(0) = swFace ‘Previously captured objectswObjects(1) = swPoint ‘Previously captured objectbResult = Measure.Calculate(swObjects)
Then grab the property of the measure that you’re afterdResult = Measure.Length (or .Radius or .Angle or .Area or…)
Measure: An Object Unto Itself
Copyright © 2009 Razorleaf Corporation www.razorleaf.com
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
Macro Features
Copyright © 2009 Razorleaf Corporation www.razorleaf.com
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
SolidWorks and .NET
Copyright © 2009 Razorleaf Corporation www.razorleaf.com
1.Collect inputs2.Perform arithmetic and logic calculations3.Attach to SolidWorks4.Pass values to SolidWorks5.Force regeneration of model6.Retrieve values from SolidWorks7.Perform further calculations8.Iterate with SolidWorks as needed9.Generate outputs
Design Automation Steps
Copyright © 2009 Razorleaf Corporation www.razorleaf.com
• 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
Concluding Tips and Techniques
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 GimbelBusiness Process
Sherpa
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).