SlideShare a Scribd company logo
Automating Your Designs Excel, VBA, and Beyond Paul Gimbel Razorleaf Corporation
OK, Fine. Here’s What We’ll Do Obligatory Introductions Overview – Automation: Why? How Much? Who? Background For Our Example Automation Choices Excel Can Do That? Gimme a V! Gimme a B! Gimme an A! Commercially Available Solutions How To Choose Questions and (if you’re lucky) Answers
Not Sure If You Should Stay Here or Go See Michael Craffey’s “Drawings For The Masses”? Free Code!!! New ways of approaching automation with the same tools What can you do with SolidWorks? What can you do with SolidWorks and Excel? What can you do with SolidWorks, Excel and VBA? What can you do if you have money? (Michael’s talking about DXF’s, PDF’s and eDrawings)
DISCLAIMER!!!  More Information Than Time There is so much that you can do with this stuff!! Liz wouldn’t give me a 14 hour session I may have to talk faster than the guy at the end of a car commercial Everything is documented in the PowerPoint Download it from the SolidWorks World Site Download it from the Razorleaf Site (link on the handout) Give me a business card and I’ll email it to you Read the Presenter Notes Come on up after the session with any questions Take my business card...take a few and hand them around
Paul Gimbel, Business Process Sherpa Yes, that is my official title Certified SolidWorks Professional (since program inception) Certified SolidWorks Trainer/Support Technician (10 years) Only Certified DriveWorks Enterprise Implementer RuleStream Implementer (Certification Program Pending) VB and SolidWorks API developer as needed Business Development Leader – Design Automation Group Business Development Leader – Business Process Group Plays Well With Others…most of the time
Where To Start “It’s All About The Process” – The Sherpa The most important thing to understand is the design process Immediately followed by the notion that it might change Map out your current process AS IT IS PERFORMED! Not how the ISO document says it  should  be performed. Ask around to the people that actually do the work Understand and prioritize your goals Time to market? Customizability? Standardization? Just lazy? Plan your vision – What will life look like?
Yup. This Slide AGAIN Process Technology From “Technology Induced Change And The Line Manager”, Dr. Eliot Levinson Mutual Adaptation Pure Automation Flexible Technical Implementation Non-Implementation Rigid Flexible Rigid
“It’s All About The Process” Don’t just write a macro to push the same buttons Re-evaluate what SolidWorks can really do for you See the two previous (hidden) slides Download the presentation and open it in PowerPoint See my two previous SolidWorks World presentations www.razorleaf.com/SWWorld/2005_pgimbel_Process.zip www.razorleaf.com/SWWorld/2006_pgimbel_Automation.zip Go see Matthew Cummins “Planning for Change: Tips and Tricks for Design Automation” @ 4:30 today
Reality Check A couple automation realities you should know about: 100% automation is generally unachievable Typically, the last 10% of automation will not be worth it Customers will always request something you didn’t plan for Your drawings are probably going to require clean-up People will fight your efforts Your end users will be even stupider than you imagined Testing will take you far longer than you expect Your system will require ongoing maintenance and updates
Your Options Pure SolidWorks functionality SolidWorks Macros Microsoft Excel (and some VBA, of course) Maximized use of Excel and VBA Custom developed application Commercially available solution partner product AutoDesk Inven…nah, who are we kidding.
Pure SolidWorks Configurations Design Tables Smart Components Mate References Design Checker SolidWorks Task Scheduler DriveWorksXpress FeatureWorks
What Do You Mean SolidWorks Has Limitations!?!? All of these functions require interaction with the user SolidWorks is required  Great for your reseller, not so great for your budget Puts non-engineers in an uncomfortable environment Requires at least some SolidWorks training Do you really want a salesperson opening your models!?!? Data management issues One file with tons of configurations? How big is that file, eh? Multiple people can’t edit one file Revision questions Save As Copy every time? What about updates?
SolidWorks Macros Designed to drive the SolidWorks User Interface Not all that automation-friendly OK to use for small functions Some 5 or 6 step operation that you want to hotkey Can be tough to share due to peoples individual settings Often requires specific pre-selections Everything plays on the screen (video performance aspect)
The Road To Excel Design Tables alone don’t address User Interface Input values as opposed to output values Advanced Excel functionality  Leverage Excel Use Excel User Interface tools Add-Ins (Analysis Pack, Solver, etc.) Data validation User Defined Functions Macros
Excel and SolidWorks – So Happy Together Three Methods To Integrate SolidWorks and Excel Design Table Embedded in the SolidWorks model Must edit through SolidWorks Edit Table In New Window to gain access to Excel MUST BE IN THE DESIGN TABLE SHEET WHEN YOU EXIT!! External Spreadsheet with Macro to drive SolidWorks Requires SolidWorks API programming Separates workbook from SolidWorks model Does not require SolidWorks (until macro is run) Shareable (through Excel Share Workbook functionality) Can be used to drive multiple SolidWorks files Can be used to drive other things as well, not just SW Spreadsheet with Macro Inserted as OLE Object
What Excel Brings To The Party (a six pack?) Formatting Charts Design Binder Easy User Interfaces Advanced equation functionality VBA Custom functions Macros Object-Oriented Programming (well, sort of)
Just A Little Bit Of Work Makes A Huge Difference Some People’s Idea of an Excel User Interface Less Than Twenty Minutes Of Work
Building User Interfaces in Excel Data Validation Lists, error and warning dialogs, tool tips Input Messages Error Messages Warning Messages In-Cell Dropdowns
Building User Interfaces in Excel Data Validation Lists, error and warning dialogs, tool tips Conditional Formatting Control user’s attention based on input
Building User Interfaces in Excel Data Validation Lists, error and warning dialogs, tool tips Conditional Formatting Control user’s attention based on input Tools, Protection Unlock/show only cells you want them to be able to change
Building User Interfaces in Excel Control Toolbox VB-style input devices that can fill in your cells Data Validation Lists, error and warning dialogs, tool tips Conditional Formatting Control user’s attention based on input Tools, Protection Unlock/show only cells you want them to be able to change
Building User Interfaces in Excel Control Toolbox VB-style input devices that can fill in your cells Data Validation Lists, error and warning dialogs, tool tips Conditional Formatting Control user’s attention based on input Tools, Protection Unlock/show only cells you want them to be able to change Pictures, Diagrams, Charts Help users understand what information they need to input F dMax
What Excel Brings To The Party (a six pack?) Formatting Charts Design Binder Easy User Interfaces Advanced equation functionality VBA Custom functions Macros Object-Oriented Programming (well, sort of)
Calculations in Excel Name Your Cells and Ranges Just as in SolidWorks, it makes equations easier to read Add Comments In adjoining cells or with the comment tool Keep your formulas simple whenever possible Multiple calculation steps are easier to troubleshoot Intelligent Layouts Don’t scatter stuff all over the place Consider cells that may need to be adjacent for lookups, etc. Give this collection of cells a single name
Working with Ranges in Excel Index: Return the value at row  n , column  m Match: Which row is this value in? Specify which order values are in (asc/desc) or exact matches Combine with Index to do a lookup on any column VLookup/HLookup: Find value in first column/row RangeLookup = FALSE: “No, I only want exact matches” RangeLookup = TRUE: “Yes, find me the closest match” VLookup(110,VoltageRange,2,FALSE) = 1.73 VLookup(290,VoltageRange,2,FALSE) = N/A# VLookup(359,VoltageRange,2,TRUE) = 3.48 360 2.9 240 1.73 110 Impedance Voltage 2.9 Searches until it finds a value that is “greater than” the search value, then goes back to take the previous one.
Dealing With Unknown Quantities Count: How many numbers are in the range? CountA: How many non-blank cells are in the range? Columns/Rows: How many columns/rows are in the range? DGet: Return any value in a range based on criteria Criteria1   Criteria2  Criteria3  Criteria 4 Range “Holes” DGet(Holes,”Dia”,Criteria1) = 0.250 DGet(Holes,”Number”,Criteria2) = 2 DGet(Holes,”Number”,Criteria3) = #NUM! DGet(Holes,”Dia”,Criteria4) = #VALUE!
More Cool Excel Functions Indirect: Display range/cell based on a formula Ceiling/Floor: Rounds up/down to the next multiple SumIf: Totals all of the values in a range that meet a criteria =SumIf(ThicknessRange,”>0.25”,PriceRange) DSum: Add values from records that meet a criteria Error Trapping: IsErr IsError Error.Type IsNA IsBlank IsLogical IsNumber IsText IsNonText Type
What Excel Brings To The Party (a six pack?) Formatting Charts Design Binder Easy User Interfaces Advanced equation functionality VBA Custom functions Macros Object-Oriented Programming (well, sort of)
OK, Enough Easy Stuff…On To The VBA Use VBA to AUGMENT Excel Custom functions Macros Connections to other programs (like SolidWorks) Do As Much As You Can In Excel Easier to troubleshoot Easier to maintain Faster to develop
Custom Functions – Repetitive Calculations Tired of typing in the same equations? Public Function CylVolume(Radius As Double, Height As Double) As Double Dim Pi As Double Pi = 4 * Atn(1)   ‘ArcTangent of 1 = pi/4…I think CylVolume = Pi * Radius * Raidus * Height End Function Now you can just use: = CylVolume(Radius, Height)  or  =CylVolume($B$4, C5)  (if you haven’t been paying attention and you don’t know that you’re supposed to name your cell ranges)
Custom Functions – Fill in Excel Gaps Excel missing a function you want? No problem! Public Function Divisible(Value As Double, Divisor As Double) As Boolean   Dim Compare As Integer Compare = CInt(Value / Divisor) If Compare = (Value / Divisor) Then Divisible = True Else Divisible = False End If End Function Now all I do is put THIS in my cell: =If(Divisible(Length,StdSpacing),Length / StdSpacing,0) Note : Because we’re converting a Double to an Integer, this only works for numbers up to 32767. This was not an issue in my application as the model only supported up to 48”. But you may want to put a check in there so you don’t get overflow errors.
Custom Functions - Conversions What about converting units or data types? (or both!) Public Function FeetInches(TotalInches As Double) As String Dim Feet As Integer Dim Inches As Double Feet = Application.WorksheetFunction.RoundDown(TotalInches / 12,0) FeetInches = Feet & “’ “ Inches = (TotalInches – (Feet * 12)) If Inches > 0 Then FeetInches = FeetInches & “- “ & Inches & chr(34)  ’(34 is ASCII for “) End If End Function Now you can use the equation: =“LENGTH = “ & FeetInches(Length) To get: LENGTH = 4’ – 6.125” The example in your handout actually picks up on increments of 1/32”
Custom Functions - Handling Sets of Data Excel Cannot Really Handle Arrays Of Data It can do ranges, but ranges need a known number of cells Paul’s Solution: Store lists of values in a single cell (ex. “1.25|17|21.1375|9”) Create a series of functions to manipulate these lists ListQty – How many entities are in the list? GetListValue – Give me the  n th member of the list. FindValueInList – Is this value in the list? Where? SortList, FlipList, InsertIntoList – Control the order RangeToList – Convert a range of cells into a list Don’t like the pipe (|) character?  Just change it to whatever you like in the SPLIT/JOIN commands.
How To Program In VBA The Ultimate Process For Non-Programmers: Determine what you want your program/code snippet to do Think of some “keywords” to describe it (if you know the functions you need to use, you’re ahead of the game) http://www.google.com   (add “VBA” and/or “Excel” to search) Ctrl-C Ctrl-V Tweak Also look to Excel VBA and SW API Help files. They’re actually helpful.  I know! I was shocked, too. Also check out www.krugle.org
Programming Tips For Excel DOCUMENT THE $#^@ OUT OF EVERYTHING!!! Anything after an apostrophe (‘) is a comment…use them!! Option Explicit It’s the “Require Fully Defined Sketches” of the VBA world Intellisense…good. Typing…bad. If you don’t see the option that you need, something’s wrong. Compile and Test Often Programmatic sanity checks Insert Test Code Use Debug Tools Step Into, Step Over, Watches, Breakpoints
The Object Browser
Getting Around In Excel With VBA To access a named cell (you named them all, right!!?!?) Thickness = Worksheets(“Calcs”).Range(“TestCell”).Value Running through the cells in a named range Dim MyCell As Excel.Range  ‘Even a single cell is treated as a range For Each MyCell in Worksheets(“Calcs”).Range(“TestRange”) Total = Total + MyCell.Value Next MyCell  ‘Looping through the TestRange What if you have rows (i.e. a multi-column range)? Dim MyRow As Excel.Range ‘We’re going to cycle through the rows For Each MyRow in Worksheets(“Calcs”).Range(“TestRange”).Rows Total = Total + MyRow.Cells(1,3).Value  ‘Row 1, Column 3 of the range Next MyRow  ‘Looping through the TestRange
Absolute Row and Column References Can I just put in Row and Column references, like: Thickness = Worksheets(“Sheet1”).Range(“A1:A1”).Value Thickness = Worksheets(“Sheet1”).Cells(4,9).Value Sure, but I would have to slap you silly Readability…Minus 10 style points What if the range moves…Minus 10 style points Debugging…Minus 10 style points Scalability…Minus 10 style points Portability…Minus 10 style points Chances of anyone else understanding your code…Minus 30!
Object-Oriented Programming  (or some facsimile thereof) One of the hardest, most confusing concepts in programming (Or so I’m told) Class  – A definition of something like a window or bolt Property  – A parameter value that an object has Method  – Something that an object can do Collection  – A bunch of objects, like an array, just of objects Dot  (.) – Something you will type a lot of Separates an object from its property or method Ex. Bolt.Length or Window.Pane.item(“top”).Glass.Thickness Instantiate  – To make a real thing as defined by a class Ex. Upper Flange Bolt #3 or Kitchen Window Over Sink Those are then called “instances” and “objects”
The SolidWorks API is Sort Of Object-Oriented Example: Dim swApp As SldWorks.SldWorks Dim swModel As SldWorks.ModelDoc2 Dim swFeatMgr As SldWorks.FeatureManager Dim swFeat As SldWorks.Feature Dim swWzdHole As WizardHoleFeatureData2 Set swApp = Application.SldWorks Set swModel = swApp.ActiveDoc Set swFeatMgr = swModel.FeatureManager … Set swWzdHole = swFeatMgr.CreateDefinition(swFmHoleWzd) swWzdHole.HoleDepth = 0.15 swWzdHole.HoleDiameter = 0.0555 … Set swFeat = swFeatMgr.CreateFeature(swWzdHole) … Early Bound Object Declarations aka “Fully Qualified” (+5 Style Points) Object assignment (instantiation) requires the keyword  Set HoleDepth and HoleDiameter are  Properties  of the WizardHoleFeatureData2 object CreateDefinition and CreateFeature are  Methods  (functions)
Object-Oriented Programming and You (an example) Windows are made up of components Glass Panes How many panes?  Dunno. 1, 2, 3, maybe 4 How thick are they?  Each one could be different. What kind of glass?  Each one could be different. Complex algorithms required Other parts, too But we’ll just focus on the glass Product is ever evolving
Option 1: Loooooong Lists Assume the MAXIMUM number of components Brute force all of the values out Imagine this with a dozen instances, each with a dozen parameters!   That’s  … um … carry the three … plus eleven … over  e  to the x … That’s a LOT of cells!  (yes, I know it’s 144, unless you’re counting the unit and label cells in which case it’s 432, but if you don’t count the blank cells, then it’s an even 300, plus another 12 for the component title cells, which technically are one because they’re merged, but you can count them as three if you want making 336.)
Option 1: Macro Code Your macro code has a limitation built in For Counter = 1 to 4 Do… You constantly have to test to see how many panes there are If Worksheets(“Calculations”).range(“Thickness3”).Value = “” Then… If you add the ability for another pane, you’re searching all through the code to replace the 4’s with 5’s Your programming is in one long lump o’code Lots of variables, or constant read/write to worksheets Debugging is a lot harder, more variables to watch
Option 2: Object-Oriented Approach Window Object has GlassPane objects How many? An unlimited number!!! Each window has a Window object,  an object that holds all of the GlassPanes  and an object for each GlassPane Table can expand as much as it needs to
Option 2: Macro Code No quantity limits!! For Counter = 1 to Window.GlassPanes.Count Do No guessing how many panes there are You already have the ability for an unlimited number of panes, no code upgrades needed Programming is nice an organized Write it once, use it as many times as you want No extra variables, no need to constantly write to the worksheets Window.GlassPanes.Item(n).Thickness Watching an object shows all of its properties (easy debug)
OOP Excel Style: The Basics Think of your class structure like your assy structure In most cases Right-Select, Insert, Class Module Define your properties and methods Instantiate as needed Always use fully qualified names  ex. Window.GlassPanes.Item(n).GlassPane.Thickness Easier to read and debug (yes, it’s longer) Intellisense keeps you from having to type
Defining a Class Standard methods to put in: Class_Initialize: Gets run each time this class is instantiated Public Sub Class_Initialize() Anything you want to happen automatically End Sub Name Property: Can be used to identify an item in a collection Have a variable in the class called  sName  (indicates it’s a string) Private sName As String Public Property Get Name () As String Name = sName End Property Public Property Let Name (uName As String) sName = uName End Property Get  allows you to get the value Let  allows you to set the value
Collection Classes Class_Initialize creates the collection Private mcolGlassPanes As Collection Private Sub Class_Initialize () Set mcolGlassPanes = New Collection End Sub Add Private Sub Add(uGlassPane As GlassPane) mcolGlassPanes.Add uGlassPane End Sub Remove Private Sub Remove (ByVal varID As Variant) mcolGlassPanes.remove varID End Sub You can pass this an index number or the value of the Name property
Alternate Add Method Instead of passing an object, you can just pass values Private mGlassPane As GlassPane Public Sub Add(uThickness As Double) Set mGlassPane = New GlassPane mGlassPane.Thickness = uThickness mcolGlassPanes.Add mGlassPane End Sub
Collection Classes (Continued) Item: allows you to refer to a single element of the collection Public Function Item(ByVal varID As Variant) As GlassPane Set item = mcolGlassPanes(varID) End Function Count: Returns the number of elements in the collection Public Get Count() As Long Count = mcolGlassPanes.Count End Property You can pass this an index number or the value of the Name property
Ready? Set? … Instantiate!! To add another panel (Using a nice User Interface) Private Sub cmdAddPane_Click() Dim iName As String ‘The input name Dim iType As String ‘The input type Dim iThk As Double ‘The input thickness iName = Worksheets(“Input”).Range(“InputName”).Value iType = Worksheets(“Input”).Range(“InputType”).Value iThk = Worksheets(“Input”).Range(“InputThk”).Value cPanes.Add iName, iThk, iType Worksheets(“Input”).Range(“InputName”).Value = “” Worksheets(“Input”).Range(“InputType”).Value = “” Worksheets(“Input”).Range(“InputThk”).Value = 0 Msgbox(“You have successfully added a pane! Aren’t you just so cool?”) End Sub *Coating property removed from code due to space, but it’s done the same way. *
Auto-Instantiation Take a whole list of cell values and create the panes: Dim cPanes As GlassPanes Dim MyRow As Excel.Range  ‘Excel range object Dim iName, iType, iCoating As String ‘The input values Dim iThk As Double ‘The input thickness For Each MyRow in Worksheets(“Input”).Range(“Glass”).Rows iName = MyRow.Cells(1,1).Value iThk = MyRow.Cells(1,2).Value iType = MyRow.Cells(1,3).Value iCoating = MyRow.Cells(1,4).Value cPanes.Add iName, iThks, iType, iCoating Next MyRow
Accessing Your Instances Use  Me  when referring to the object that you’re in Ex. In the code for the Window class, you would use: Me.ModelNumber (property of the Window class) Me.CalculateRValue (method of the Window class) Me.GlassPanes.Count (method of a child of the Window class) Use the  Item  method by passing an index or a Name dThk = Me.GlassPanes.Item(3).Thickness dThk = Me.GlassPanels.Item(“Outside”).Thickness Real Life Example: Me.Walls.Item(“Front”).Panels.item(Me.Walls.item(“Front”).Panels.Count).CeilingLocks.item(1).LocalLocation
VERY Quick Lesson In Debugging Run the code to see if it works. If it does, great! Otherwise, it will show you where the problem is or just stare at you. Use Breakpoints at each major stage to see where it trips Click in this column to add a breakpoint
VERY Quick Lesson In Debugging Run the code to see if it works. If it does, great! Otherwise, it will show you where the problem is or just stare at you. Use Breakpoints at each major stage to see where it trips Break at the last working area and Step (Shift+F8) through If it trips in a function or subroutine, use F8 to step into it Still can’t figure it out? Watch the values as you approach the problem spot by hovering over variables or “add watch”
Error Trapping (If It Can Happen, It Will) Test for conditions to ensure that they don’t happen Anywhere that something could go wrong Bad Input is #1 source of problems Calculations Gone Wrong is a close second Collection.Count = 0 / Nothing Selected rounds out the trifecta  On Error GoTo (just in case) Public Sub RunMe() On Error GoTo errhandler … errhandler:  If err.Number > 0 Then msgBox(“Dude! “ & err.Description) End Sub Check it out! The errors in VBA are an object.
Where To Go From Here? Build some test code to test portions of your code Comment out lines Hard code values Use msgbox() Use a macro to kick everything off Right-Select, Add Module to house the macro Have the macro be on an event (ex. cmdButton_Click) The macro will instantiate your top-level Your top-level can instantiate everything else or User-interaction can instantiate components as required
Connecting to SolidWorks Add the SolidWorks library to your project Tools, Macros, Visual Basic Editor Tools, References, SolidWorks 2008 Type Library Now you have SW Intellisense Define your SolidWorks App Dim swApp As SldWorks.SldWorks Establish a SolidWorks object Attaches to an existing session Launches SW if it is not open Set swApp = CreateObject("SldWorks.Application")
Things To Note About SolidWorks API Programming Fairly well documented in the API Help File Macro Record, not really as helpful as everyone thinks All units are in METERS!! ERROR TRAP EVERYTHING!!! Check EVERY object   If Not(Object Is Nothing) Then… Check your document type Check any preselects Verify data types before passing anything to SolidWorks Check data types of anything you receive from SolidWorks Beware of anything that may require user interaction Close everything out when you are done (Not enough time to go in depth into SolidWorks API programming, sorry)
Automation Approaches Use SolidWorks to solve complex geometry calculations Mass properties Interferences/Clearances Multi-dimensional sketches Do as much OUTSIDE of SolidWorks as possible SolidWorks is sloooooow (comparatively speaking, of course)
So What About VB or .NET? Yeah, I promised I would address it. Mostly the same techniques as Excel. Slightly better performance But SolidWorks is almost always the slowest link A little more secure (user’s can’t muck about in the code) Extensible to the web ASP.NET More difficult to maintain Recompiling code Requires Visual Studio (or equivalent) and knowledge thereof Managing versions of the .NET Framework
Even Better Than Excel VBA? (Maybe) SolidWorks Solutions Partners Help with the creation of user interfaces Help with the capture and storage of rules Help with the driving of SolidWorks models Help with the creation of derivative SolidWorks drawings Roll out solutions to non-SolidWorks users Provide server components to generate the SolidWorks data
What To Look For In A SolidWorks Solution Partner How much programming do you want to do? Rules can be expressed in VB.NET, Excel, Proprietary languages Some allow programming to supplement the application How do you want the users to interact? Some run inside of SolidWorks (requires seats, some SW knowhow)  Do you need multiple people to specify a new unit simultaneously? Some run inside of a SolidWorks model, and cannot do this Some use SQL Server back ends to help support this Where are the models going to be generated? Server components free up your machine/require fewer SW seats Do you want/need a Internet/intranet browser-based interface?
Thanks for doing your part, you sure are smart! Got Questions? Thank you! FILL OUT YOUR EVALUATION FORMS I get $5 for each one turned in! Paul Gimbel Business Process Sherpa [email_address] www.razorleaf.com

More Related Content

PPTX
Automating With Excel An Object Oriented Approach
PPTX
SolidWorks Modeling for Design Automation
PPTX
Solving Iterative Design Problems with TactonWorks
PPTX
Automating SolidWorks with Excel
PPT
COE2010 Razorleaf Setting Up Catalogs in ENOVIA SmarTeam
PDF
Testing for Agility: Bringing Testing into Everything
PDF
An Introduction to Kanban
PDF
Inside Behavior Driven Development
Automating With Excel An Object Oriented Approach
SolidWorks Modeling for Design Automation
Solving Iterative Design Problems with TactonWorks
Automating SolidWorks with Excel
COE2010 Razorleaf Setting Up Catalogs in ENOVIA SmarTeam
Testing for Agility: Bringing Testing into Everything
An Introduction to Kanban
Inside Behavior Driven Development

Viewers also liked (20)

PDF
AU 2015: Enterprise, Beam Me Up: Inphi's Enterprise PLM Solution (PPT)
PPT
Sww 2006 Redesigning Processes For Solid Works
PDF
AU 2014: Autodesk PLM 360 Success Story with Inphi (PPT)
PPTX
Autdoesk PLM 360 to PDM Integration with Jitterbit
PPTX
Merging PLM and Microsoft SharePoint Strategies from GPDIS 2009
PPTX
Managing CATIA V5 in PDM... Simply for COE Ask The Expert
PPTX
Discovering New Product Introduction (NPI) using Autodesk Fusion Lifecycle
PPTX
Demystifying The Solid Works Api
PPTX
COE 2016: 10 Cool Tools for 2016
PPTX
Open Source PLM
PPTX
Deploying DriveWorks Throughout the Organization
PPTX
COE 2016: Technical Data Migration Made Simple
PPTX
DriveWorks World 2016 - 13 lessons in 12 years
PDF
Design Automation - Simple Solid Works Solutions To Practical Programmatic Pa...
PPTX
Automated Design Validation The Solid Works Api
PPTX
Moving from Document Management to BOM Management
PPTX
Connecting SolidWorks EPDM and ENOVIA V6
PPTX
3DVIA Composer for Assembly Instruction Storyboards
PPT
COE2010 Razorleaf ENOVIA SmarTeam Deployment at AS&E
PPTX
COE2010 Razorleaf Tweaking 3DLive on ENOVIA SmarTeam
AU 2015: Enterprise, Beam Me Up: Inphi's Enterprise PLM Solution (PPT)
Sww 2006 Redesigning Processes For Solid Works
AU 2014: Autodesk PLM 360 Success Story with Inphi (PPT)
Autdoesk PLM 360 to PDM Integration with Jitterbit
Merging PLM and Microsoft SharePoint Strategies from GPDIS 2009
Managing CATIA V5 in PDM... Simply for COE Ask The Expert
Discovering New Product Introduction (NPI) using Autodesk Fusion Lifecycle
Demystifying The Solid Works Api
COE 2016: 10 Cool Tools for 2016
Open Source PLM
Deploying DriveWorks Throughout the Organization
COE 2016: Technical Data Migration Made Simple
DriveWorks World 2016 - 13 lessons in 12 years
Design Automation - Simple Solid Works Solutions To Practical Programmatic Pa...
Automated Design Validation The Solid Works Api
Moving from Document Management to BOM Management
Connecting SolidWorks EPDM and ENOVIA V6
3DVIA Composer for Assembly Instruction Storyboards
COE2010 Razorleaf ENOVIA SmarTeam Deployment at AS&E
COE2010 Razorleaf Tweaking 3DLive on ENOVIA SmarTeam
Ad

Similar to Sww 2008 Automating Your Designs Excel, Vba And Beyond (20)

PPT
Automation Of Reporting And Alerting
PDF
Access tips access and sql part 4 building select queries on-the-fly
PPTX
No more Three Tier - A path to a better code for Cloud and Azure
PPTX
...and thus your forms automagically disappeared
PPT
Intro to Application Express
PPTX
CA ERwin Data Modeler End User Presentation
PDF
Data Science for non techies using KNIME 08 Weeks Training
PPT
Getting Unstuck: Working with Legacy Code and Data
PPT
Building Applications for SQL Server 2008
PDF
OSCON 2014: Data Workflows for Machine Learning
PDF
Data Workflows for Machine Learning - Seattle DAML
PPTX
#SPSEMEA SharePoint & jQuery - What I wish I would have known a year ago..
PPT
Grasping The LightSwitch Paradigm
PPTX
13 - Panorama Necto 14 building models - visualization & data discovery solu...
PDF
Top10 Salesforce.com Admin Tools
PPTX
Domain oriented development
PPT
The Magic Of Application Lifecycle Management In Vs Public
PPTX
Better User Experience with .NET
PDF
Clean architecture with asp.net core
PPT
User Driven Software Architecture
Automation Of Reporting And Alerting
Access tips access and sql part 4 building select queries on-the-fly
No more Three Tier - A path to a better code for Cloud and Azure
...and thus your forms automagically disappeared
Intro to Application Express
CA ERwin Data Modeler End User Presentation
Data Science for non techies using KNIME 08 Weeks Training
Getting Unstuck: Working with Legacy Code and Data
Building Applications for SQL Server 2008
OSCON 2014: Data Workflows for Machine Learning
Data Workflows for Machine Learning - Seattle DAML
#SPSEMEA SharePoint & jQuery - What I wish I would have known a year ago..
Grasping The LightSwitch Paradigm
13 - Panorama Necto 14 building models - visualization & data discovery solu...
Top10 Salesforce.com Admin Tools
Domain oriented development
The Magic Of Application Lifecycle Management In Vs Public
Better User Experience with .NET
Clean architecture with asp.net core
User Driven Software Architecture
Ad

More from Razorleaf Corporation (12)

PDF
COE 2017: Your first 3DEXPERIENCE customization
PDF
COE 2017: Atomic Content
PDF
Three Approaches to Integration that Deliver Greater PLM Value
PPTX
COE 2016 Live demo How to get to full Digitalization
PPTX
ENOVIA v6 R2013x Tips and Tricks
PDF
AU 2015: Enterprise, Beam Me Up: Inphi's Enterprise PLM Solution (Tech Paper)
PDF
AU 2014: Autodesk PLM 360 Success Story with Inphi (TECH PAPER)
PPTX
Automating Analysis with the API
PPTX
COE2010 Razorleaf ENOVIA SmarTeam and V6 Readiness
PPT
COE2010 Razorleaf SmarTeam Attribute Mappings for Word and Excel
PPT
Paul Gimbel - Presentation Opening Quotes
PPT
Sww 2007 Lets Get Ready To Automate
COE 2017: Your first 3DEXPERIENCE customization
COE 2017: Atomic Content
Three Approaches to Integration that Deliver Greater PLM Value
COE 2016 Live demo How to get to full Digitalization
ENOVIA v6 R2013x Tips and Tricks
AU 2015: Enterprise, Beam Me Up: Inphi's Enterprise PLM Solution (Tech Paper)
AU 2014: Autodesk PLM 360 Success Story with Inphi (TECH PAPER)
Automating Analysis with the API
COE2010 Razorleaf ENOVIA SmarTeam and V6 Readiness
COE2010 Razorleaf SmarTeam Attribute Mappings for Word and Excel
Paul Gimbel - Presentation Opening Quotes
Sww 2007 Lets Get Ready To Automate

Recently uploaded (20)

PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Machine learning based COVID-19 study performance prediction
PDF
Unlocking AI with Model Context Protocol (MCP)
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
Modernizing your data center with Dell and AMD
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
Approach and Philosophy of On baking technology
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PPTX
Big Data Technologies - Introduction.pptx
PDF
Review of recent advances in non-invasive hemoglobin estimation
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Reach Out and Touch Someone: Haptics and Empathic Computing
Diabetes mellitus diagnosis method based random forest with bat algorithm
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
The Rise and Fall of 3GPP – Time for a Sabbatical?
Machine learning based COVID-19 study performance prediction
Unlocking AI with Model Context Protocol (MCP)
“AI and Expert System Decision Support & Business Intelligence Systems”
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Modernizing your data center with Dell and AMD
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Approach and Philosophy of On baking technology
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
The AUB Centre for AI in Media Proposal.docx
Encapsulation_ Review paper, used for researhc scholars
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Big Data Technologies - Introduction.pptx
Review of recent advances in non-invasive hemoglobin estimation

Sww 2008 Automating Your Designs Excel, Vba And Beyond

  • 1. Automating Your Designs Excel, VBA, and Beyond Paul Gimbel Razorleaf Corporation
  • 2. OK, Fine. Here’s What We’ll Do Obligatory Introductions Overview – Automation: Why? How Much? Who? Background For Our Example Automation Choices Excel Can Do That? Gimme a V! Gimme a B! Gimme an A! Commercially Available Solutions How To Choose Questions and (if you’re lucky) Answers
  • 3. Not Sure If You Should Stay Here or Go See Michael Craffey’s “Drawings For The Masses”? Free Code!!! New ways of approaching automation with the same tools What can you do with SolidWorks? What can you do with SolidWorks and Excel? What can you do with SolidWorks, Excel and VBA? What can you do if you have money? (Michael’s talking about DXF’s, PDF’s and eDrawings)
  • 4. DISCLAIMER!!! More Information Than Time There is so much that you can do with this stuff!! Liz wouldn’t give me a 14 hour session I may have to talk faster than the guy at the end of a car commercial Everything is documented in the PowerPoint Download it from the SolidWorks World Site Download it from the Razorleaf Site (link on the handout) Give me a business card and I’ll email it to you Read the Presenter Notes Come on up after the session with any questions Take my business card...take a few and hand them around
  • 5. Paul Gimbel, Business Process Sherpa Yes, that is my official title Certified SolidWorks Professional (since program inception) Certified SolidWorks Trainer/Support Technician (10 years) Only Certified DriveWorks Enterprise Implementer RuleStream Implementer (Certification Program Pending) VB and SolidWorks API developer as needed Business Development Leader – Design Automation Group Business Development Leader – Business Process Group Plays Well With Others…most of the time
  • 6. Where To Start “It’s All About The Process” – The Sherpa The most important thing to understand is the design process Immediately followed by the notion that it might change Map out your current process AS IT IS PERFORMED! Not how the ISO document says it should be performed. Ask around to the people that actually do the work Understand and prioritize your goals Time to market? Customizability? Standardization? Just lazy? Plan your vision – What will life look like?
  • 7. Yup. This Slide AGAIN Process Technology From “Technology Induced Change And The Line Manager”, Dr. Eliot Levinson Mutual Adaptation Pure Automation Flexible Technical Implementation Non-Implementation Rigid Flexible Rigid
  • 8. “It’s All About The Process” Don’t just write a macro to push the same buttons Re-evaluate what SolidWorks can really do for you See the two previous (hidden) slides Download the presentation and open it in PowerPoint See my two previous SolidWorks World presentations www.razorleaf.com/SWWorld/2005_pgimbel_Process.zip www.razorleaf.com/SWWorld/2006_pgimbel_Automation.zip Go see Matthew Cummins “Planning for Change: Tips and Tricks for Design Automation” @ 4:30 today
  • 9. Reality Check A couple automation realities you should know about: 100% automation is generally unachievable Typically, the last 10% of automation will not be worth it Customers will always request something you didn’t plan for Your drawings are probably going to require clean-up People will fight your efforts Your end users will be even stupider than you imagined Testing will take you far longer than you expect Your system will require ongoing maintenance and updates
  • 10. Your Options Pure SolidWorks functionality SolidWorks Macros Microsoft Excel (and some VBA, of course) Maximized use of Excel and VBA Custom developed application Commercially available solution partner product AutoDesk Inven…nah, who are we kidding.
  • 11. Pure SolidWorks Configurations Design Tables Smart Components Mate References Design Checker SolidWorks Task Scheduler DriveWorksXpress FeatureWorks
  • 12. What Do You Mean SolidWorks Has Limitations!?!? All of these functions require interaction with the user SolidWorks is required Great for your reseller, not so great for your budget Puts non-engineers in an uncomfortable environment Requires at least some SolidWorks training Do you really want a salesperson opening your models!?!? Data management issues One file with tons of configurations? How big is that file, eh? Multiple people can’t edit one file Revision questions Save As Copy every time? What about updates?
  • 13. SolidWorks Macros Designed to drive the SolidWorks User Interface Not all that automation-friendly OK to use for small functions Some 5 or 6 step operation that you want to hotkey Can be tough to share due to peoples individual settings Often requires specific pre-selections Everything plays on the screen (video performance aspect)
  • 14. The Road To Excel Design Tables alone don’t address User Interface Input values as opposed to output values Advanced Excel functionality Leverage Excel Use Excel User Interface tools Add-Ins (Analysis Pack, Solver, etc.) Data validation User Defined Functions Macros
  • 15. Excel and SolidWorks – So Happy Together Three Methods To Integrate SolidWorks and Excel Design Table Embedded in the SolidWorks model Must edit through SolidWorks Edit Table In New Window to gain access to Excel MUST BE IN THE DESIGN TABLE SHEET WHEN YOU EXIT!! External Spreadsheet with Macro to drive SolidWorks Requires SolidWorks API programming Separates workbook from SolidWorks model Does not require SolidWorks (until macro is run) Shareable (through Excel Share Workbook functionality) Can be used to drive multiple SolidWorks files Can be used to drive other things as well, not just SW Spreadsheet with Macro Inserted as OLE Object
  • 16. What Excel Brings To The Party (a six pack?) Formatting Charts Design Binder Easy User Interfaces Advanced equation functionality VBA Custom functions Macros Object-Oriented Programming (well, sort of)
  • 17. Just A Little Bit Of Work Makes A Huge Difference Some People’s Idea of an Excel User Interface Less Than Twenty Minutes Of Work
  • 18. Building User Interfaces in Excel Data Validation Lists, error and warning dialogs, tool tips Input Messages Error Messages Warning Messages In-Cell Dropdowns
  • 19. Building User Interfaces in Excel Data Validation Lists, error and warning dialogs, tool tips Conditional Formatting Control user’s attention based on input
  • 20. Building User Interfaces in Excel Data Validation Lists, error and warning dialogs, tool tips Conditional Formatting Control user’s attention based on input Tools, Protection Unlock/show only cells you want them to be able to change
  • 21. Building User Interfaces in Excel Control Toolbox VB-style input devices that can fill in your cells Data Validation Lists, error and warning dialogs, tool tips Conditional Formatting Control user’s attention based on input Tools, Protection Unlock/show only cells you want them to be able to change
  • 22. Building User Interfaces in Excel Control Toolbox VB-style input devices that can fill in your cells Data Validation Lists, error and warning dialogs, tool tips Conditional Formatting Control user’s attention based on input Tools, Protection Unlock/show only cells you want them to be able to change Pictures, Diagrams, Charts Help users understand what information they need to input F dMax
  • 23. What Excel Brings To The Party (a six pack?) Formatting Charts Design Binder Easy User Interfaces Advanced equation functionality VBA Custom functions Macros Object-Oriented Programming (well, sort of)
  • 24. Calculations in Excel Name Your Cells and Ranges Just as in SolidWorks, it makes equations easier to read Add Comments In adjoining cells or with the comment tool Keep your formulas simple whenever possible Multiple calculation steps are easier to troubleshoot Intelligent Layouts Don’t scatter stuff all over the place Consider cells that may need to be adjacent for lookups, etc. Give this collection of cells a single name
  • 25. Working with Ranges in Excel Index: Return the value at row n , column m Match: Which row is this value in? Specify which order values are in (asc/desc) or exact matches Combine with Index to do a lookup on any column VLookup/HLookup: Find value in first column/row RangeLookup = FALSE: “No, I only want exact matches” RangeLookup = TRUE: “Yes, find me the closest match” VLookup(110,VoltageRange,2,FALSE) = 1.73 VLookup(290,VoltageRange,2,FALSE) = N/A# VLookup(359,VoltageRange,2,TRUE) = 3.48 360 2.9 240 1.73 110 Impedance Voltage 2.9 Searches until it finds a value that is “greater than” the search value, then goes back to take the previous one.
  • 26. Dealing With Unknown Quantities Count: How many numbers are in the range? CountA: How many non-blank cells are in the range? Columns/Rows: How many columns/rows are in the range? DGet: Return any value in a range based on criteria Criteria1 Criteria2 Criteria3 Criteria 4 Range “Holes” DGet(Holes,”Dia”,Criteria1) = 0.250 DGet(Holes,”Number”,Criteria2) = 2 DGet(Holes,”Number”,Criteria3) = #NUM! DGet(Holes,”Dia”,Criteria4) = #VALUE!
  • 27. More Cool Excel Functions Indirect: Display range/cell based on a formula Ceiling/Floor: Rounds up/down to the next multiple SumIf: Totals all of the values in a range that meet a criteria =SumIf(ThicknessRange,”>0.25”,PriceRange) DSum: Add values from records that meet a criteria Error Trapping: IsErr IsError Error.Type IsNA IsBlank IsLogical IsNumber IsText IsNonText Type
  • 28. What Excel Brings To The Party (a six pack?) Formatting Charts Design Binder Easy User Interfaces Advanced equation functionality VBA Custom functions Macros Object-Oriented Programming (well, sort of)
  • 29. OK, Enough Easy Stuff…On To The VBA Use VBA to AUGMENT Excel Custom functions Macros Connections to other programs (like SolidWorks) Do As Much As You Can In Excel Easier to troubleshoot Easier to maintain Faster to develop
  • 30. Custom Functions – Repetitive Calculations Tired of typing in the same equations? Public Function CylVolume(Radius As Double, Height As Double) As Double Dim Pi As Double Pi = 4 * Atn(1) ‘ArcTangent of 1 = pi/4…I think CylVolume = Pi * Radius * Raidus * Height End Function Now you can just use: = CylVolume(Radius, Height) or =CylVolume($B$4, C5) (if you haven’t been paying attention and you don’t know that you’re supposed to name your cell ranges)
  • 31. Custom Functions – Fill in Excel Gaps Excel missing a function you want? No problem! Public Function Divisible(Value As Double, Divisor As Double) As Boolean Dim Compare As Integer Compare = CInt(Value / Divisor) If Compare = (Value / Divisor) Then Divisible = True Else Divisible = False End If End Function Now all I do is put THIS in my cell: =If(Divisible(Length,StdSpacing),Length / StdSpacing,0) Note : Because we’re converting a Double to an Integer, this only works for numbers up to 32767. This was not an issue in my application as the model only supported up to 48”. But you may want to put a check in there so you don’t get overflow errors.
  • 32. Custom Functions - Conversions What about converting units or data types? (or both!) Public Function FeetInches(TotalInches As Double) As String Dim Feet As Integer Dim Inches As Double Feet = Application.WorksheetFunction.RoundDown(TotalInches / 12,0) FeetInches = Feet & “’ “ Inches = (TotalInches – (Feet * 12)) If Inches > 0 Then FeetInches = FeetInches & “- “ & Inches & chr(34) ’(34 is ASCII for “) End If End Function Now you can use the equation: =“LENGTH = “ & FeetInches(Length) To get: LENGTH = 4’ – 6.125” The example in your handout actually picks up on increments of 1/32”
  • 33. Custom Functions - Handling Sets of Data Excel Cannot Really Handle Arrays Of Data It can do ranges, but ranges need a known number of cells Paul’s Solution: Store lists of values in a single cell (ex. “1.25|17|21.1375|9”) Create a series of functions to manipulate these lists ListQty – How many entities are in the list? GetListValue – Give me the n th member of the list. FindValueInList – Is this value in the list? Where? SortList, FlipList, InsertIntoList – Control the order RangeToList – Convert a range of cells into a list Don’t like the pipe (|) character? Just change it to whatever you like in the SPLIT/JOIN commands.
  • 34. How To Program In VBA The Ultimate Process For Non-Programmers: Determine what you want your program/code snippet to do Think of some “keywords” to describe it (if you know the functions you need to use, you’re ahead of the game) http://www.google.com (add “VBA” and/or “Excel” to search) Ctrl-C Ctrl-V Tweak Also look to Excel VBA and SW API Help files. They’re actually helpful. I know! I was shocked, too. Also check out www.krugle.org
  • 35. Programming Tips For Excel DOCUMENT THE $#^@ OUT OF EVERYTHING!!! Anything after an apostrophe (‘) is a comment…use them!! Option Explicit It’s the “Require Fully Defined Sketches” of the VBA world Intellisense…good. Typing…bad. If you don’t see the option that you need, something’s wrong. Compile and Test Often Programmatic sanity checks Insert Test Code Use Debug Tools Step Into, Step Over, Watches, Breakpoints
  • 37. Getting Around In Excel With VBA To access a named cell (you named them all, right!!?!?) Thickness = Worksheets(“Calcs”).Range(“TestCell”).Value Running through the cells in a named range Dim MyCell As Excel.Range ‘Even a single cell is treated as a range For Each MyCell in Worksheets(“Calcs”).Range(“TestRange”) Total = Total + MyCell.Value Next MyCell ‘Looping through the TestRange What if you have rows (i.e. a multi-column range)? Dim MyRow As Excel.Range ‘We’re going to cycle through the rows For Each MyRow in Worksheets(“Calcs”).Range(“TestRange”).Rows Total = Total + MyRow.Cells(1,3).Value ‘Row 1, Column 3 of the range Next MyRow ‘Looping through the TestRange
  • 38. Absolute Row and Column References Can I just put in Row and Column references, like: Thickness = Worksheets(“Sheet1”).Range(“A1:A1”).Value Thickness = Worksheets(“Sheet1”).Cells(4,9).Value Sure, but I would have to slap you silly Readability…Minus 10 style points What if the range moves…Minus 10 style points Debugging…Minus 10 style points Scalability…Minus 10 style points Portability…Minus 10 style points Chances of anyone else understanding your code…Minus 30!
  • 39. Object-Oriented Programming (or some facsimile thereof) One of the hardest, most confusing concepts in programming (Or so I’m told) Class – A definition of something like a window or bolt Property – A parameter value that an object has Method – Something that an object can do Collection – A bunch of objects, like an array, just of objects Dot (.) – Something you will type a lot of Separates an object from its property or method Ex. Bolt.Length or Window.Pane.item(“top”).Glass.Thickness Instantiate – To make a real thing as defined by a class Ex. Upper Flange Bolt #3 or Kitchen Window Over Sink Those are then called “instances” and “objects”
  • 40. The SolidWorks API is Sort Of Object-Oriented Example: Dim swApp As SldWorks.SldWorks Dim swModel As SldWorks.ModelDoc2 Dim swFeatMgr As SldWorks.FeatureManager Dim swFeat As SldWorks.Feature Dim swWzdHole As WizardHoleFeatureData2 Set swApp = Application.SldWorks Set swModel = swApp.ActiveDoc Set swFeatMgr = swModel.FeatureManager … Set swWzdHole = swFeatMgr.CreateDefinition(swFmHoleWzd) swWzdHole.HoleDepth = 0.15 swWzdHole.HoleDiameter = 0.0555 … Set swFeat = swFeatMgr.CreateFeature(swWzdHole) … Early Bound Object Declarations aka “Fully Qualified” (+5 Style Points) Object assignment (instantiation) requires the keyword Set HoleDepth and HoleDiameter are Properties of the WizardHoleFeatureData2 object CreateDefinition and CreateFeature are Methods (functions)
  • 41. Object-Oriented Programming and You (an example) Windows are made up of components Glass Panes How many panes? Dunno. 1, 2, 3, maybe 4 How thick are they? Each one could be different. What kind of glass? Each one could be different. Complex algorithms required Other parts, too But we’ll just focus on the glass Product is ever evolving
  • 42. Option 1: Loooooong Lists Assume the MAXIMUM number of components Brute force all of the values out Imagine this with a dozen instances, each with a dozen parameters! That’s … um … carry the three … plus eleven … over e to the x … That’s a LOT of cells! (yes, I know it’s 144, unless you’re counting the unit and label cells in which case it’s 432, but if you don’t count the blank cells, then it’s an even 300, plus another 12 for the component title cells, which technically are one because they’re merged, but you can count them as three if you want making 336.)
  • 43. Option 1: Macro Code Your macro code has a limitation built in For Counter = 1 to 4 Do… You constantly have to test to see how many panes there are If Worksheets(“Calculations”).range(“Thickness3”).Value = “” Then… If you add the ability for another pane, you’re searching all through the code to replace the 4’s with 5’s Your programming is in one long lump o’code Lots of variables, or constant read/write to worksheets Debugging is a lot harder, more variables to watch
  • 44. Option 2: Object-Oriented Approach Window Object has GlassPane objects How many? An unlimited number!!! Each window has a Window object, an object that holds all of the GlassPanes and an object for each GlassPane Table can expand as much as it needs to
  • 45. Option 2: Macro Code No quantity limits!! For Counter = 1 to Window.GlassPanes.Count Do No guessing how many panes there are You already have the ability for an unlimited number of panes, no code upgrades needed Programming is nice an organized Write it once, use it as many times as you want No extra variables, no need to constantly write to the worksheets Window.GlassPanes.Item(n).Thickness Watching an object shows all of its properties (easy debug)
  • 46. OOP Excel Style: The Basics Think of your class structure like your assy structure In most cases Right-Select, Insert, Class Module Define your properties and methods Instantiate as needed Always use fully qualified names ex. Window.GlassPanes.Item(n).GlassPane.Thickness Easier to read and debug (yes, it’s longer) Intellisense keeps you from having to type
  • 47. Defining a Class Standard methods to put in: Class_Initialize: Gets run each time this class is instantiated Public Sub Class_Initialize() Anything you want to happen automatically End Sub Name Property: Can be used to identify an item in a collection Have a variable in the class called sName (indicates it’s a string) Private sName As String Public Property Get Name () As String Name = sName End Property Public Property Let Name (uName As String) sName = uName End Property Get allows you to get the value Let allows you to set the value
  • 48. Collection Classes Class_Initialize creates the collection Private mcolGlassPanes As Collection Private Sub Class_Initialize () Set mcolGlassPanes = New Collection End Sub Add Private Sub Add(uGlassPane As GlassPane) mcolGlassPanes.Add uGlassPane End Sub Remove Private Sub Remove (ByVal varID As Variant) mcolGlassPanes.remove varID End Sub You can pass this an index number or the value of the Name property
  • 49. Alternate Add Method Instead of passing an object, you can just pass values Private mGlassPane As GlassPane Public Sub Add(uThickness As Double) Set mGlassPane = New GlassPane mGlassPane.Thickness = uThickness mcolGlassPanes.Add mGlassPane End Sub
  • 50. Collection Classes (Continued) Item: allows you to refer to a single element of the collection Public Function Item(ByVal varID As Variant) As GlassPane Set item = mcolGlassPanes(varID) End Function Count: Returns the number of elements in the collection Public Get Count() As Long Count = mcolGlassPanes.Count End Property You can pass this an index number or the value of the Name property
  • 51. Ready? Set? … Instantiate!! To add another panel (Using a nice User Interface) Private Sub cmdAddPane_Click() Dim iName As String ‘The input name Dim iType As String ‘The input type Dim iThk As Double ‘The input thickness iName = Worksheets(“Input”).Range(“InputName”).Value iType = Worksheets(“Input”).Range(“InputType”).Value iThk = Worksheets(“Input”).Range(“InputThk”).Value cPanes.Add iName, iThk, iType Worksheets(“Input”).Range(“InputName”).Value = “” Worksheets(“Input”).Range(“InputType”).Value = “” Worksheets(“Input”).Range(“InputThk”).Value = 0 Msgbox(“You have successfully added a pane! Aren’t you just so cool?”) End Sub *Coating property removed from code due to space, but it’s done the same way. *
  • 52. Auto-Instantiation Take a whole list of cell values and create the panes: Dim cPanes As GlassPanes Dim MyRow As Excel.Range ‘Excel range object Dim iName, iType, iCoating As String ‘The input values Dim iThk As Double ‘The input thickness For Each MyRow in Worksheets(“Input”).Range(“Glass”).Rows iName = MyRow.Cells(1,1).Value iThk = MyRow.Cells(1,2).Value iType = MyRow.Cells(1,3).Value iCoating = MyRow.Cells(1,4).Value cPanes.Add iName, iThks, iType, iCoating Next MyRow
  • 53. Accessing Your Instances Use Me when referring to the object that you’re in Ex. In the code for the Window class, you would use: Me.ModelNumber (property of the Window class) Me.CalculateRValue (method of the Window class) Me.GlassPanes.Count (method of a child of the Window class) Use the Item method by passing an index or a Name dThk = Me.GlassPanes.Item(3).Thickness dThk = Me.GlassPanels.Item(“Outside”).Thickness Real Life Example: Me.Walls.Item(“Front”).Panels.item(Me.Walls.item(“Front”).Panels.Count).CeilingLocks.item(1).LocalLocation
  • 54. VERY Quick Lesson In Debugging Run the code to see if it works. If it does, great! Otherwise, it will show you where the problem is or just stare at you. Use Breakpoints at each major stage to see where it trips Click in this column to add a breakpoint
  • 55. VERY Quick Lesson In Debugging Run the code to see if it works. If it does, great! Otherwise, it will show you where the problem is or just stare at you. Use Breakpoints at each major stage to see where it trips Break at the last working area and Step (Shift+F8) through If it trips in a function or subroutine, use F8 to step into it Still can’t figure it out? Watch the values as you approach the problem spot by hovering over variables or “add watch”
  • 56. Error Trapping (If It Can Happen, It Will) Test for conditions to ensure that they don’t happen Anywhere that something could go wrong Bad Input is #1 source of problems Calculations Gone Wrong is a close second Collection.Count = 0 / Nothing Selected rounds out the trifecta On Error GoTo (just in case) Public Sub RunMe() On Error GoTo errhandler … errhandler: If err.Number > 0 Then msgBox(“Dude! “ & err.Description) End Sub Check it out! The errors in VBA are an object.
  • 57. Where To Go From Here? Build some test code to test portions of your code Comment out lines Hard code values Use msgbox() Use a macro to kick everything off Right-Select, Add Module to house the macro Have the macro be on an event (ex. cmdButton_Click) The macro will instantiate your top-level Your top-level can instantiate everything else or User-interaction can instantiate components as required
  • 58. Connecting to SolidWorks Add the SolidWorks library to your project Tools, Macros, Visual Basic Editor Tools, References, SolidWorks 2008 Type Library Now you have SW Intellisense Define your SolidWorks App Dim swApp As SldWorks.SldWorks Establish a SolidWorks object Attaches to an existing session Launches SW if it is not open Set swApp = CreateObject("SldWorks.Application")
  • 59. Things To Note About SolidWorks API Programming Fairly well documented in the API Help File Macro Record, not really as helpful as everyone thinks All units are in METERS!! ERROR TRAP EVERYTHING!!! Check EVERY object  If Not(Object Is Nothing) Then… Check your document type Check any preselects Verify data types before passing anything to SolidWorks Check data types of anything you receive from SolidWorks Beware of anything that may require user interaction Close everything out when you are done (Not enough time to go in depth into SolidWorks API programming, sorry)
  • 60. Automation Approaches Use SolidWorks to solve complex geometry calculations Mass properties Interferences/Clearances Multi-dimensional sketches Do as much OUTSIDE of SolidWorks as possible SolidWorks is sloooooow (comparatively speaking, of course)
  • 61. So What About VB or .NET? Yeah, I promised I would address it. Mostly the same techniques as Excel. Slightly better performance But SolidWorks is almost always the slowest link A little more secure (user’s can’t muck about in the code) Extensible to the web ASP.NET More difficult to maintain Recompiling code Requires Visual Studio (or equivalent) and knowledge thereof Managing versions of the .NET Framework
  • 62. Even Better Than Excel VBA? (Maybe) SolidWorks Solutions Partners Help with the creation of user interfaces Help with the capture and storage of rules Help with the driving of SolidWorks models Help with the creation of derivative SolidWorks drawings Roll out solutions to non-SolidWorks users Provide server components to generate the SolidWorks data
  • 63. What To Look For In A SolidWorks Solution Partner How much programming do you want to do? Rules can be expressed in VB.NET, Excel, Proprietary languages Some allow programming to supplement the application How do you want the users to interact? Some run inside of SolidWorks (requires seats, some SW knowhow) Do you need multiple people to specify a new unit simultaneously? Some run inside of a SolidWorks model, and cannot do this Some use SQL Server back ends to help support this Where are the models going to be generated? Server components free up your machine/require fewer SW seats Do you want/need a Internet/intranet browser-based interface?
  • 64. Thanks for doing your part, you sure are smart! Got Questions? Thank you! FILL OUT YOUR EVALUATION FORMS I get $5 for each one turned in! Paul Gimbel Business Process Sherpa [email_address] www.razorleaf.com

Editor's Notes

  • #2: Good afternoon and welcome. We’ve got a great show for you today. Al Gore will be here to tell us how the use of 2D is depleting the ozone layer. And we’ve got Samuel L. Jackson here with clips from the sequel to the blockbuster “Snakes on a Plane.” This one’s called “Splines on a Projected Surface.” Sorry. I tried to come up with better material, but my writers are on strike. But first, we’re going to talk about Automating Your SolidWorks Designs.