0
Automating With Excel:An Object-Oriented Approach<br />Paul Gimbel<br />Razorleaf Corporation<br />
OK, Fine. Here’s What We’ll Do<br />Obligatory Introductions<br />Overview – Automation: Why? How Much? Who?<br />Backgrou...
Not Sure If You Should Stay Here or Go See Lisa and Tammy’s “Migrating to ePDM”?<br />I’ve got:<br />Free Code!!!<br />New...
DISCLAIMER!!!     More Information Than Time<br />There is so much that you can do with this stuff!!<br />Liz wouldn’t giv...
Who Is This Guy and Where Did He Come From?<br />Razorleaf Corporation<br />SolidWorks Service Partner<br />Services ONLY ...
Where To Start<br />“It’s All About The Process” – The Sherpa<br />The most important thing to understand is the design pr...
Yup. This Slide AGAIN<br />Process<br />Technology<br />From “Technology Induced Change And The Line Manager”, Dr. Eliot L...
“It’s All About The Process”<br />Don’t just write a macro to push the same buttons, think bigger!<br />Re-evaluate what S...
Reality Check<br />A couple automation realities you should know about:<br />100% automation is generally unachievable<br ...
Your Options<br />Pure SolidWorks functionality<br />SolidWorks Macros<br />Microsoft Excel (and some VBA, of course)<br /...
Pure SolidWorks<br />Configurations<br />Design Tables<br />Sensors<br />Equations<br />Smart Components<br />Mate Referen...
What Do You Mean SolidWorks Has Limitations!?!?<br />All of these functions require interaction with the user<br />SolidWo...
SolidWorks Macros<br />Designed to drive the SolidWorks User Interface<br />Not all that automation-friendly<br />OK to us...
The Road To Excel<br />Design Tables alone don’t address<br />User Interface (Configuration Manager, to a small extent)<br...
Excel and SolidWorks – So Happy Together<br />Three Methods To Integrate SolidWorks and Excel<br />Design Table<br />Embed...
What Excel Brings To The Party (a six pack?)<br />Formatting<br />Charts<br />Easy User Interfaces<br />Advanced equation ...
Just A Little Bit Of Work Makes A Huge Difference<br />Some People’s Idea of an Excel User Interface<br />Less Than Twenty...
Building User Interfaces in Excel<br /><ul><li>Data Validation
Lists, error and warning dialogs, tool tips</li></ul>In-Cell Dropdowns<br />Input Messages<br />Error Messages<br />Warnin...
Building User Interfaces in Excel<br /><ul><li>Conditional Formatting
Control user’s attention based on input
Data Validation
Lists, error and warning dialogs, tool tips</li></li></ul><li>Building User Interfaces in Excel<br /><ul><li>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</li></li></ul><li>Building User Interfaces in Excel<br /><ul><li...
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
Control Toolbox
VB-Style input device that can fill in your cells</li></li></ul><li>Building User Interfaces in Excel<br />dMax<br />F<br ...
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</li></ul>Control Toolbox<br />VB-style input devices that can fi...
Help users understand what information they need to input</li></li></ul><li>What Excel Brings To The Party (a six pack?)<b...
Calculations in Excel<br />Name Your Cells and Ranges<br />Just as in SolidWorks, it makes equations easier to read<br />A...
2.9<br />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<br />Count: How many numbers are in the range?<br />CountA: How many non-blank cells are i...
More Cool Excel Functions<br />Indirect: Display range/cell based on a formula<br />Ceiling/Floor: Rounds up/down to the n...
IsNumber
IsText
IsNonText
Type</li></ul>27<br />
What Excel Brings To The Party (a six pack?)<br />Formatting<br />Charts<br />Design Binder<br />Easy User Interfaces<br /...
OK, Enough Easy Stuff…On To The VBA<br />Use VBA to AUGMENT Excel<br />Custom functions<br />Macros<br />Connections to ot...
Custom Functions – Repetitive Calculations<br />Tired of typing in the same equations?<br />PublicFunctionCylVolume(Radius...
Custom Functions – Fill in Excel Gaps<br />Excel missing a function you want? No problem!<br />PublicFunction Divisible(Va...
Custom Functions - Conversions<br />What about converting units or data types? (or both!)<br />Public Function FeetInches(...
Custom Functions - Handling Sets of Data<br />Excel Cannot Really Handle Arrays Of Data<br />It can do ranges, but ranges ...
How To Program In VBA<br />The Ultimate Process For Non-Programmers:<br />Determine what you want your program/code snippe...
Programming Tips For Excel<br />DOCUMENT THE $#^@ OUT OF EVERYTHING!!!<br />Anything after an apostrophe (‘) is a comment…...
The Object Browser<br />36<br />
Getting Around In Excel With VBA<br />To access a named cell (you named them all, right!!?!?)<br />Thickness = Worksheets(...
Absolute Row and Column References<br />Can I just put in Row and Column references, like:<br />Thickness = Worksheets(“Sh...
Object-Oriented Programming**<br />“Everything you need to do in the SolidWorks API has to be done by or to an object.”<br...
The SolidWorks API Object Example (VBA)<br />Early Bound Object Declarations aka “Fully Qualified” (+5 Style Points)<br />...
Upcoming SlideShare
Loading in...5
×

Automating With Excel An Object Oriented Approach

7,256

Published on

SolidWorks World Presentation from Paul Gimbel at Razorleaf. This presentation deals with the use of Microsoft Excel and Visual Basic for Applications as a front end to driving SolidWorks geometry in a design automation implementation.

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
7,256
On Slideshare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
261
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide
  • Here’s the mandatory and cliché review of me and my company. Razorleaf is a services-only company providing implementation and customization, training and support for PDM including EPDM, SmarTeam, Aras, and Matrix, as well as Design Automation (that’s my specialty) including DriveWorks, Tacton, and custom solutions. As I said, services-only, so I won’t be trying to sell you anything, don’t worry.I am Paul Gimbel, known in the SolidWorks community as simply “The Sherpa.” I’ve been to every SolidWorks World, presented at quite a few of them. A trainer and demojock since the original, SolidWorks 95. So yes, I’m old, and yes, I’m starting to look it.
  • Transcript of "Automating With Excel An Object Oriented Approach"

    1. 1. Automating With Excel:An Object-Oriented Approach<br />Paul Gimbel<br />Razorleaf Corporation<br />
    2. 2. OK, Fine. Here’s What We’ll Do<br />Obligatory Introductions<br />Overview – Automation: Why? How Much? Who?<br />Background For Our Example<br />Automation Choices<br />Excel Can Do That?<br />Gimme a V! Gimme a B! Gimme an A!<br />Commercially Available Solutions<br />How To Choose a Design Automation Strategy<br />Questions and (if you’re lucky) Answers<br />
    3. 3. Not Sure If You Should Stay Here or Go See Lisa and Tammy’s “Migrating to ePDM”?<br />I’ve got:<br />Free Code!!!<br />New ways of approaching automation with the same tools<br />What can you do with SolidWorks?<br />What can you do with SolidWorks and Excel?<br />What can you do with SolidWorks, Excel and VBA?<br />What can you do if you have money?<br />And the overriding theme of What Is OOP (and how will it save me 15% or more on my car insurance)<br />(Lisa and Tammy are showing case studies of migrating data into ePDM without the use of custom code down in 201 A-B.)<br />
    4. 4. DISCLAIMER!!! More Information Than Time<br />There is so much that you can do with this stuff!!<br />Liz wouldn’t give me a 14 hour session<br />I may have to talk faster than the guy at the end of a car commercial<br />Everything is documented in the PowerPoint<br />Download it from the SolidWorks World Site (eventually)<br />Download it from the Razorleaf Site (www.razorleaf.com)<br />Give me a business card and I’ll email it to you (the ppt, not your card)<br />Read the Presenter Notes!!<br />Come on up after the session with any questions<br />Follow me around the hallways until you can stop me<br />Take my business card...take a few and hand them around<br />
    5. 5. Who Is This Guy and Where Did He Come From?<br />Razorleaf Corporation<br />SolidWorks Service Partner<br />Services ONLY (we’re not trying to sell you anything, we’re neutral)<br />Data Management (EPDM, SmarTeam, Aras)<br />Design Automation (DriveWorks, Tacton)<br />Workflow Automation (Microsoft SharePoint and Tools)<br />Paul Gimbel (aka “The Sherpa”)<br />10+ years as Demo Jock, Applications Engineer, Trainer, Support Tech<br />5 years as Design Automation Implementer<br />Specializing in SolidWorks, DriveWorks, Tacton, Custom Programming<br />(THERE! Now I can report this trip as reimbursable.)<br />The <br />Sherpa<br />
    6. 6. Where To Start<br />“It’s All About The Process” – The Sherpa<br />The most important thing to understand is the design process<br />Immediately followed by the notion that it might change<br />Map out your current process<br />AS IT IS PERFORMED! Not how the ISO document says it should be performed.<br />Ask around to the people that actually do the work<br />Understand and prioritize your goals<br />Time to market? Customizability? Standardization? Just lazy?<br />Plan your vision – What will life look like?<br />
    7. 7. Yup. This Slide AGAIN<br />Process<br />Technology<br />From “Technology Induced Change And The Line Manager”, Dr. Eliot Levinson<br />7<br />
    8. 8. “It’s All About The Process”<br />Don’t just write a macro to push the same buttons, think bigger!<br />Re-evaluate what SolidWorks can really do for you<br />See the two previous (hidden) slides<br />Download the presentation and open it in PowerPoint<br />See some of my previous SolidWorks World presentations (www.razorleaf.com)<br />Redesigning Processes for SolidWorks – SWW 2006<br />Lets Get Ready To Automate – SWW 2007<br />Automating Your Designs – SWW 2008<br />Using SolidWorks and API to Drive Complex Calculations – SWW 2009<br />Demystifying the SolidWorks API – SWW 2010<br />Automating Design Validation with the SolidWorks API – SWW 2010<br />
    9. 9. Reality Check<br />A couple automation realities you should know about:<br />100% automation is generally unachievable<br />Typically, the last 10% of automation will not be worth it<br />Customers will always request something you didn’t plan for<br />Your drawings are probably going to require clean-up<br />People will fight your efforts<br />Your end users will be even stupider than you imagined<br />Testing will take you far longer than you expect<br />Your system will require ongoing maintenance and updates<br />
    10. 10. Your Options<br />Pure SolidWorks functionality<br />SolidWorks Macros<br />Microsoft Excel (and some VBA, of course)<br />Maximized use of Excel and VBA<br />Custom developed application<br />Commercially available solution partner product<br />AutoDesk Inven…nah, who are we kidding.<br />
    11. 11. Pure SolidWorks<br />Configurations<br />Design Tables<br />Sensors<br />Equations<br />Smart Components<br />Mate References<br />Design Checker<br />SolidWorks Task Scheduler<br />DriveWorksXpress<br />FeatureWorks<br />
    12. 12. What Do You Mean SolidWorks Has Limitations!?!?<br />All of these functions require interaction with the user<br />SolidWorks is required <br />Great for your reseller, not so great for your budget<br />Puts non-engineers in an uncomfortable environment<br />Requires at least some SolidWorks training<br />Do you really want a salesperson opening your models!?!?<br />Data management issues<br />One file with tons of configurations?<br />How big is that file, eh?<br />Multiple people can’t edit one file<br />Revision questions<br />Save As Copy every time?<br />What about updates?<br />
    13. 13. SolidWorks Macros<br />Designed to drive the SolidWorks User Interface<br />Not all that automation-friendly<br />OK to use for small functions<br />Can be tough to share due to peoples individual settings<br />Often requires specific pre-selections<br />Everything plays on the screen (video performance aspect)<br />
    14. 14. The Road To Excel<br />Design Tables alone don’t address<br />User Interface (Configuration Manager, to a small extent)<br />Input values as opposed to output values<br />Advanced Excel functionality <br />Leverage Excel<br />Use Excel User Interface tools<br />Data validation<br />User Defined Functions<br />Macros<br />Add-Ins (Analysis Pack, Solver, etc.)<br />
    15. 15. Excel and SolidWorks – So Happy Together<br />Three Methods To Integrate SolidWorks and Excel<br />Design Table<br />Embedded in the SolidWorks model<br />Must edit through SolidWorks<br />Edit Table In New Window to gain access to Excel<br />MUST BE IN THE DESIGN TABLE SHEET WHEN YOU EXIT!!<br />External Spreadsheet with Macro to drive SolidWorks<br />Requires SolidWorks API programming<br />Separates workbook from SolidWorks model<br />Does not require SolidWorks (until macro is run)<br />Shareable (through Excel Share Workbook functionality)<br />Can be used to drive multiple SolidWorks files<br />Can be used to drive other things as well, not just SW<br />Spreadsheet with Macro Inserted as OLE Object<br />
    16. 16. What Excel Brings To The Party (a six pack?)<br />Formatting<br />Charts<br />Easy User Interfaces<br />Advanced equation functionality<br />VBA<br />Custom functions<br />Macros<br />Object-Oriented Programming (well, sort of)<br />
    17. 17. Just A Little Bit Of Work Makes A Huge Difference<br />Some People’s Idea of an Excel User Interface<br />Less Than Twenty Minutes Of Work<br />
    18. 18. Building User Interfaces in Excel<br /><ul><li>Data Validation
    19. 19. Lists, error and warning dialogs, tool tips</li></ul>In-Cell Dropdowns<br />Input Messages<br />Error Messages<br />Warning Messages<br />
    20. 20. Building User Interfaces in Excel<br /><ul><li>Conditional Formatting
    21. 21. Control user’s attention based on input
    22. 22. Data Validation
    23. 23. Lists, error and warning dialogs, tool tips</li></li></ul><li>Building User Interfaces in Excel<br /><ul><li>Data Validation
    24. 24. Lists, error and warning dialogs, tool tips
    25. 25. Conditional Formatting
    26. 26. Control user’s attention based on input
    27. 27. Tools, Protection
    28. 28. Unlock/show only cells you want them to be able to change</li></li></ul><li>Building User Interfaces in Excel<br /><ul><li>Data Validation
    29. 29. Lists, error and warning dialogs, tool tips
    30. 30. Conditional Formatting
    31. 31. Control user’s attention based on input
    32. 32. Tools, Protection
    33. 33. Unlock/show only cells you want them to be able to change
    34. 34. Control Toolbox
    35. 35. VB-Style input device that can fill in your cells</li></li></ul><li>Building User Interfaces in Excel<br />dMax<br />F<br /><ul><li>Data Validation
    36. 36. Lists, error and warning dialogs, tool tips
    37. 37. Conditional Formatting
    38. 38. Control user’s attention based on input
    39. 39. Tools, Protection
    40. 40. Unlock/show only cells you want them to be able to change</li></ul>Control Toolbox<br />VB-style input devices that can fill in your cells<br /><ul><li>Pictures, Diagrams, Charts
    41. 41. Help users understand what information they need to input</li></li></ul><li>What Excel Brings To The Party (a six pack?)<br />Formatting<br />Charts<br />Design Binder<br />Easy User Interfaces<br />Advanced equation functionality<br />VBA<br />Custom functions<br />Macros<br />Object-Oriented Programming (well, sort of)<br />
    42. 42. Calculations in Excel<br />Name Your Cells and Ranges<br />Just as in SolidWorks, it makes equations easier to read<br />Add Comments<br />In adjoining cells or with the comment tool<br />Keep your formulas simple whenever possible<br />Multiple calculation steps are easier to troubleshoot<br />Intelligent Layouts<br />Don’t scatter stuff all over the place<br />Consider cells that may need to be adjacent for lookups, etc.<br />Give this collection of cells a single name<br />
    43. 43. 2.9<br />Searches until it finds a value that is “greater than” the search value, then goes back to take the previous one.<br />Working with Ranges in Excel<br />Index: Return the value at row n, column m<br />Match: Which row is this value in?<br />Specify which order values are in (asc/desc) or exact matches<br />Combine with Index to do a lookup on any column<br />VLookup/HLookup: Find value in first column/row<br />RangeLookup = FALSE: “No, I only want exact matches”<br />RangeLookup = TRUE: “Yes, find me the closest match”<br />VLookup(110,VoltageRange,2,FALSE) =<br />1.73<br />VLookup(290,VoltageRange,2,FALSE) =<br />N/A#<br />VLookup(359,VoltageRange,2,TRUE) =<br />25<br />
    44. 44. Dealing With Unknown Quantities<br />Count: How many numbers are in the range?<br />CountA: How many non-blank cells are in the range?<br />Columns/Rows: How many columns/rows are in the range?<br />DGet: Return any value in a range based on criteria<br />Range “Holes”<br />DGet(Holes,”Dia”,Criteria1) =<br />0.250<br />DGet(Holes,”Number”,Criteria2) =<br />2<br />DGet(Holes,”Number”,Criteria3) =<br />#NUM!<br />DGet(Holes,”Dia”,Criteria4) =<br />#VALUE!<br />Criteria1Criteria2 Criteria3 Criteria 4<br />26<br />
    45. 45. More Cool Excel Functions<br />Indirect: Display range/cell based on a formula<br />Ceiling/Floor: Rounds up/down to the next multiple<br />SumIf: Totals all of the values in a range that meet a criteria<br />=SumIf(ThicknessRange,”&gt;0.25”,PriceRange)<br />DSum: Add values from records that meet a criteria<br />Error Trapping:<br />IsErr<br />IsError<br />Error.Type<br />IsNA<br />IsBlank<br /><ul><li>IsLogical
    46. 46. IsNumber
    47. 47. IsText
    48. 48. IsNonText
    49. 49. Type</li></ul>27<br />
    50. 50. What Excel Brings To The Party (a six pack?)<br />Formatting<br />Charts<br />Design Binder<br />Easy User Interfaces<br />Advanced equation functionality<br />VBA<br />Custom functions<br />Macros<br />Object-Oriented Programming (well, sort of)<br />28<br />
    51. 51. OK, Enough Easy Stuff…On To The VBA<br />Use VBA to AUGMENT Excel<br />Custom functions<br />Macros<br />Connections to other programs (like SolidWorks)<br />Do As Much As You Can In Excel<br />Easier to troubleshoot<br />Easier to maintain<br />Faster to develop<br />29<br />
    52. 52. Custom Functions – Repetitive Calculations<br />Tired of typing in the same equations?<br />PublicFunctionCylVolume(Radius AsDouble, Height AsDouble) AsDouble<br />Dim Pi AsDouble<br />Pi = 4 * Atn(1) ‘ArcTangent of 1 = pi/4…I think<br />CylVolume = Pi * Radius * Raidus * Height<br />EndFunction<br />Now you can just use:<br />= CylVolume(Radius, Height) <br /> or <br />=CylVolume($B$4, C5) <br /> (if you haven’t been paying attention and you don’t know that you’re supposed to name your cell ranges)<br />30<br />
    53. 53. Custom Functions – Fill in Excel Gaps<br />Excel missing a function you want? No problem!<br />PublicFunction Divisible(Value AsDouble, Divisor AsDouble) AsBoolean<br />Dim Compare AsInteger<br />Compare = CInt(Value / Divisor)<br />If Compare = (Value / Divisor) Then<br /> Divisible = True<br />Else<br /> Divisible = False<br />EndIf<br />EndFunction<br />Now all I do is put THIS in my cell:<br />=If(Divisible(Length,StdSpacing),Length / StdSpacing,0)<br />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.<br />31<br />
    54. 54. Custom Functions - Conversions<br />What about converting units or data types? (or both!)<br />Public Function FeetInches(TotalInchesAsDouble) AsString<br />Dim Feet AsInteger<br />Dim Inches AsDouble<br />Feet = Application.WorksheetFunction.RoundDown(TotalInches / 12,0)<br />FeetInches = Feet & “’ “<br />Inches = (TotalInches – (Feet * 12))<br />If Inches &gt; 0 Then<br />FeetInches = FeetInches & “- “ & Inches & chr(34) ’(34 is ASCII for “)<br />EndIf<br />EndFunction<br />Now you can use the equation:<br />=“LENGTH = “ & FeetInches(Length)<br />To get:<br />LENGTH = 4’ – 6.125”<br />The example in your handout actually picks up on increments of 1/32”<br />32<br />
    55. 55. Custom Functions - Handling Sets of Data<br />Excel Cannot Really Handle Arrays Of Data<br />It can do ranges, but ranges need a known number of cells<br />Paul’s Solution:<br />Store lists of values in a single cell (ex. “1.25|17|21.1375|9”)<br />Create a series of functions to manipulate these lists<br />ListQty – How many entities are in the list?<br />GetListValue – Give me the nth member of the list.<br />FindValueInList – Is this value in the list? Where?<br />SortList, FlipList, InsertIntoList – Control the order<br />RangeToList – Convert a range of cells into a list<br />Don’t like the pipe (|) character? <br />Just change it to whatever you like in the SPLIT/JOIN commands.<br />33<br />
    56. 56. How To Program In VBA<br />The Ultimate Process For Non-Programmers:<br />Determine what you want your program/code snippet to do<br />Think of some “keywords” to describe it (if you know the functions you need to use, you’re ahead of the game)<br />http://www.google.com (add “VBA” and/or “Excel” to search)<br />Ctrl-C<br />Ctrl-V<br />Tweak<br />Also check out<br />www.krugle.org<br />Also look to Excel VBA and SW API Help files. <br />They’re actually helpful. I know! I was shocked, too.<br />34<br />
    57. 57. Programming Tips For Excel<br />DOCUMENT THE $#^@ OUT OF EVERYTHING!!!<br />Anything after an apostrophe (‘) is a comment…use them!!<br />Option Explicit<br />It’s the “Require Fully Defined Sketches” of the VBA world<br />Intellisense…good. Typing…bad.<br />If you don’t see the option that you need, something’s wrong.<br />Compile and Test Often<br />Programmatic sanity checks<br />Insert Test Code<br />Use Debug Tools<br />Step Into, Step Over, Watches, Breakpoints<br />35<br />
    58. 58. The Object Browser<br />36<br />
    59. 59. Getting Around In Excel With VBA<br />To access a named cell (you named them all, right!!?!?)<br />Thickness = Worksheets(“Calcs”).Range(“TestCell”).Value<br />Running through the cells in a named range<br />Dim MyCell As Excel.Range ‘Even a single cell is treated as a range<br />For Each MyCell in Worksheets(“Calcs”).Range(“TestRange”)<br /> Total = Total + MyCell.Value<br />Next MyCell ‘Looping through the TestRange<br />What if you have rows (i.e. a multi-column range)?<br />Dim MyRow As Excel.Range ‘We’re going to cycle through the rows<br />For Each MyRow in Worksheets(“Calcs”).Range(“TestRange”).Rows<br /> Total = Total + MyRow.Cells(1,3).Value ‘Row 1, Column 3 of the range<br />Next MyRow ‘Looping through the TestRange<br />37<br />
    60. 60. Absolute Row and Column References<br />Can I just put in Row and Column references, like:<br />Thickness = Worksheets(“Sheet1”).Range(“A1:A1”).Value<br />Thickness = Worksheets(“Sheet1”).Cells(4,9).Value<br />Sure, but I would have to slap you silly<br />Readability…Minus 10 style points<br />What if the range moves…Minus 10 style points<br />Debugging…Minus 10 style points<br />Scalability…Minus 10 style points<br />Portability…Minus 10 style points<br />Chances of anyone else understanding your code…Minus 30!<br />38<br />
    61. 61. Object-Oriented Programming**<br />“Everything you need to do in the SolidWorks API has to be done by or to an object.”<br />Class – A definition (blueprint) of something (think: blank spec for a washer or bolt)<br />Interface – A more generic definition incorporating multiple classes (ex. Hardware)<br />Object – A specific instance of a class (completed spec - ex. 1/4-20 x 3 SHCS)<br />Property – A parameter value that an object has (ex. Diameter)<br />Method – Something (sub or function) that an object can do (ex. Install)<br />Accessor – A method used to get an object (ex. GetFeature, GetChildren)<br />Dot(.) –Separates an object from its property or method or “child” objects<br />Ex. Bolt.Length or Bolt.Thread.item(“Lead”).Pitch<br />Instantiate – To make a real thing as defined by a class<br />Ex. Upper Flange Bolt #3 or Rear Axle Nut<br />Those are then called “instances” and “objects”<br />**To appease any true code junkies out there. VBA doesn’t REALLY support full OOP with inheritance and polymorphism, but this is a DEMYSTIFYING session. I don’t want to MYSTIFY this stuff any more than it is.<br />
    62. 62. The SolidWorks API Object Example (VBA)<br />Early Bound Object Declarations aka “Fully Qualified” (+5 Style Points)<br />Object assignment (instantiation) requires the keyword Set in VBA only<br />HoleDepth and HoleDiameter are Properties<br />of the WizardHoleFeatureData2 object<br />Example: Creating a Hole Wizard Hole<br />Dim swApp As SldWorks.SldWorks<br />Dim swModel As SldWorks.ModelDoc2<br />Dim swFeatMgr As SldWorks.FeatureManager<br />Dim swFeat As SldWorks.Feature<br />Dim swWzdHole As WizardHoleFeatureData2<br />Set swApp = Application.SldWorks<br />Set swModel = swApp.ActiveDoc<br />Set swFeatMgr = swModel.FeatureManager<br />…more code here…<br />Set swWzdHole = swFeatMgr.CreateDefinition(swFmHoleWzd)<br />swWzdHole.HoleDepth = 0.15<br />swWzdHole.HoleDiameter = 0.0555<br />…<br />Set swFeat = swFeatMgr.CreateFeature(swWzdHole)<br />…more code here…<br />CreateDefinition and CreateFeature are Methods (functions)<br />
    63. 63. Object-Oriented Programming and You (an example)<br />Windows are made up of components<br />Glass Panes<br />How many panes? <br />Dunno. 1, 2, 3, maybe 4<br />How thick are they? <br />Each one could be different.<br />What kind of glass? <br />Each one could be different.<br />Complex algorithms required<br />Other parts, too<br />But we’ll just focus on the glass<br />Product is ever evolving<br />41<br />
    64. 64. Option 1: Loooooong Lists<br />Assume the MAXIMUM number of components<br />Brute force all of the values out<br />Imagine this with a dozen instances, each with a dozen parameters!<br />That’s … um … carry the three … plus eleven … over e to the x …<br />That’s a LOT of cells! <br />(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.)<br />42<br />
    65. 65. Option 1: Macro Code<br />Your macro code has a limitation built in<br />For Counter = 1 to 4 Do…<br />You constantly have to test to see how many panes there are<br />If Worksheets(“Calculations”).range(“Thickness3”).Value = “” Then…<br />If you add the ability for another pane, you’re searching all through the code to replace the 4’s with 5’s<br />Your programming is in one long lump o’code<br />Lots of variables, or constant read/write to worksheets<br />Debugging is a lot harder, more variables to watch<br />43<br />
    66. 66. Option 2: Object-Oriented Approach<br />Window Object has GlassPane objects<br />How many? An unlimited number!!!<br />Table can expand as much as it needs to<br />Each window has a Window object, <br />an object that holds all of the GlassPanes <br />and an object for each GlassPane<br />44<br />
    67. 67. Option 2: Macro Code<br />No quantity limits!!<br />For Counter = 1 to Window.GlassPanes.Count Do<br />No guessing how many panes there are<br />You already have the ability for an unlimited number of panes, no code upgrades needed<br />Programming is nice an organized<br />Write it once, use it as many times as you want<br />No extra variables, no need to constantly write to the worksheets<br />Window.GlassPanes.Item(n).Thickness<br />Watching an object shows all of its properties (easy debug)<br />45<br />
    68. 68. OOP Excel Style: The Basics<br />Think of your class structure like your assy structure<br />In most cases<br />Right-Select, Insert, Class Module<br />Define your properties and methods<br />Instantiate as needed<br />Always use fully qualified names <br />ex. Window.GlassPanes.Item(n).GlassPane.Thickness<br />Easier to read and debug (yes, it’s longer)<br />Intellisense keeps you from having to type<br />46<br />
    69. 69. Defining a Class<br />Get allows you to get the value<br />Let allows you to set the value<br />Standard methods to put in:<br />Class_Initialize: Gets run each time this class is instantiated<br />Public Sub Class_Initialize()<br /> Anything you want to happen automatically<br />End Sub<br />Name Property: Can be used to identify an item in a collection<br />Have a variable in the class called sName (indicates it’s a string)<br />Private sNameAs String<br />Public Property Get Name () As String<br />Name = sName<br />End Property<br />Public Property Let Name (uNameAs String)<br />sName = uName<br />End Property<br />47<br />
    70. 70. Collection Classes<br />You can pass this an index number or the value of the Name property<br />Class_Initialize creates the collection<br />Private mcolGlassPanesAs Collection<br />Private Sub Class_Initialize ()<br />Set mcolGlassPanes = New Collection<br />End Sub<br />Add<br />Private Sub Add(uGlassPane As GlassPane)<br />mcolGlassPanes.AdduGlassPane<br />End Sub<br />Remove<br />Private Sub Remove (ByValvarIDAs Variant)<br />mcolGlassPanes.removevarID<br />End Sub<br />48<br />
    71. 71. Alternate Add Method<br />Instead of passing an object, you can just pass values<br />Private mGlassPane As GlassPane<br />Public Sub Add(uThicknessAs Double)<br /> Set mGlassPane = New GlassPane<br />mGlassPane.Thickness = uThickness<br />mcolGlassPanes.AddmGlassPane<br />End Sub<br />49<br />
    72. 72. Collection Classes (Continued)<br />Item: allows you to refer to a single element of the collection<br />Public Function Item(ByValvarIDAsVariant) AsGlassPane<br />Set item = mcolGlassPanes(varID)<br />End Function<br />Count: Returns the number of elements in the collection<br />Public Get Count() As Long<br />Count = mcolGlassPanes.Count<br />End Property<br />You can pass this an index number or the value of the Name property<br />50<br />
    73. 73. Ready? Set? … Instantiate!!<br />To add another panel (Using a nice User Interface)<br />PrivateSubcmdAddPane_Click()<br />DimiNameAsString‘The input name<br />DimiTypeAsString‘The input type<br />DimiThkAsDouble‘The input thickness<br />iName = Worksheets(“Input”).Range(“InputName”).Value<br />iType = Worksheets(“Input”).Range(“InputType”).Value<br />iThk = Worksheets(“Input”).Range(“InputThk”).Value<br />cPanes.AddiName, iThk, iType<br />Worksheets(“Input”).Range(“InputName”).Value = “”<br />Worksheets(“Input”).Range(“InputType”).Value = “”<br />Worksheets(“Input”).Range(“InputThk”).Value = 0<br />Msgbox(“You have successfully added a pane! Aren’t you just so cool?”)<br />End Sub<br />*<br />*Coating property removed from code due to space, but it’s done the same way.<br />51<br />
    74. 74. Auto-Instantiation<br />Take a whole list of cell values and create the panes:<br />Dim cPanes As GlassPanes<br />Dim MyRow As Excel.Range‘Excel range object<br />Dim iName, iType, iCoating As String‘The input values<br />Dim iThk As Double‘The input thickness<br />For Each MyRow in Worksheets(“Input”).Range(“Glass”).Rows<br />iName = MyRow.Cells(1,1).Value<br />iThk = MyRow.Cells(1,2).Value<br />iType = MyRow.Cells(1,3).Value<br />iCoating = MyRow.Cells(1,4).Value<br />cPanes.AddiName, iThks, iType, iCoating<br />Next MyRow<br />52<br />
    75. 75. Accessing Your Instances<br />Use Me when referring to the object that you’re in<br />Ex. In the code for the Window class, you would use:<br />Me.ModelNumber (property of the Window class)<br />Me.CalculateRValue (method of the Window class)<br />Me.GlassPanes.Count (method of a child of the Window class)<br />Use the Item method by passing an index or a Name<br />dThk = Me.GlassPanes.Item(3).Thickness<br />dThk = Me.GlassPanels.Item(“Outside”).Thickness<br />Real Life Example:<br />Me.Walls.Item(“Front”).Panels.item(Me.Walls.item(“Front”).Panels.Count).CeilingLocks.item(1).LocalLocation<br />53<br />
    76. 76. VERY Quick Lesson In Debugging<br />Click in this column to add a breakpoint<br />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.<br />Use Breakpoints at each major stage to see where it trips<br />54<br />
    77. 77. VERY Quick Lesson In Debugging<br />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.<br />Use Breakpoints at each major stage to see where it trips<br />Break at the last working area and Step (Shift+F8) through<br />If it trips in a function or subroutine, use F8 to step into it<br />Still can’t figure it out? Watch the values as you approach the problem spot by hovering over variables or “add watch”<br />55<br />
    78. 78. Error Trapping (If It Can Happen, It Will)<br />Check it out! The errors in VBA are an object. <br />Test for conditions to ensure that they don’t happen<br />Anywhere that something could go wrong<br />Bad Input is #1 source of problems<br />Calculations Gone Wrong is a close second<br />Collection.Count = 0 / Nothing Selected rounds out the trifecta<br />On Error GoTo (just in case)<br />Public Sub RunMe()<br />On Error GoToerrhandler<br />…<br />errhandler: <br /> If err.Number &gt; 0 Then msgBox(“Dude! “ & err.Description)<br />End Sub<br />56<br />
    79. 79. Where To Go From Here?<br />Build some test code to test portions of your code<br />Comment out lines<br />Hard code values<br />Use msgbox(), Immediate Window (?), Breakpoints, Step Through<br />Use a macro to kick everything off<br />Right-Select, Add Module to house the macro<br />Have the macro be on an event (ex. cmdButton_Click)<br />The macro will instantiate your top-level<br />Your top-level can instantiate everything else or<br />User-interaction can instantiate components as required<br />57<br />
    80. 80. Connecting to SolidWorks<br />Add the SolidWorks library to your project<br />Tools, Macros, Visual Basic Editor<br />Tools, References, SolidWorks 2010 Type Library<br />Now you have SW Intellisense<br />Define your SolidWorks App<br />Dim swApp As SldWorks.SldWorks<br />Establish a SolidWorks object<br />Attaches to an existing session<br />Launches SW if it is not open<br />Set swApp = CreateObject(&quot;SldWorks.Application&quot;)<br />58<br />
    81. 81. Things To Note About SolidWorks API Programming<br />(Not enough time to go in depth into SolidWorks API programming, sorry)<br />Fairly well documented in the API Help File<br />Macro Record, good start, but not really as helpful as everyone thinks<br />All units are in METERS!!<br />ERROR TRAP EVERYTHING!!!<br />Check EVERY object If Not(Object Is Nothing) Then…<br />Check your document type<br />Check any preselects<br />Verify data types before passing anything to SolidWorks<br />Check data types of anything you receive from SolidWorks<br />Beware of anything that may require user interaction<br />Close everything out when you are done<br />Check out my presentation yesterday at 1:30pm!! (www.razorleaf.com )<br />59<br />
    82. 82. Automation Approaches<br />Use SolidWorks to solve complex geometry calculations<br />Mass properties<br />Interferences/Clearances<br />Multi-dimensional sketches<br />Do as much OUTSIDE of SolidWorks as possible<br />SolidWorks is sloooooow (comparatively speaking, of course)<br />60<br />
    83. 83. So What About VB.NET or C#?<br />SolidWorks runs and even records VBA, VB.NET and C#.NET macros<br />Microsoft Office…not so much (VBA to eternity and beyooooooond!)<br />Mostly the same techniques as VBA<br />OOP to the next level (although you really need to be good to see it)<br />Slightly better performance<br />But SolidWorks is almost always the slowest link<br />Extensible to the web ASP.NET<br />Is everything moving towards .NET? Um, well, yeah, actually.<br />Conversion from VBA to VB.NET? Pretty easy (C#, not so much)<br />Learning .NET when you know VBA? Pretty easy (C#, not so much)<br />Working in VBA when you know .NET? Pretty frustrating<br />What about C#? More symbolic, more rigid, more professional and polished<br />61<br />
    84. 84. DriveWorks Ltd.<br />Product Name: DriveWorks, DriveWorksSolo<br />Tacton Systems AB<br />Product Name: TactonWorks <br />ACATEC Software GmbH<br />Product Name: POWERCONFIGURATOR <br />Albiani<br />Product Name: iNorming<br />CadWorks Software Oy Ltd<br />Product Name: AutomateWorks®<br />Citius Corporation<br />Product Name: KBMax<br />Configure One, Inc.<br />Product Name: Configure One<br />Nuovamacut<br />Product Name: RPMWorks<br />Power2, Inc.<br />Product Name: power2design <br />REITEC GmbH<br />Product Name: Confit Product Configurator<br />VEST, Inc<br />Product Name: MDTools 900 Series <br />VISIONKBE<br />Product Name: KBEWorks<br />SolidWorks Solutions Partners<br />Help with the creation of user interfaces<br />Help with the capture and storage of rules<br />Help with the driving of SolidWorks models<br />Help with the creation of derivative SolidWorks drawings<br />Roll out solutions to non-SolidWorks users<br />Provide server components to generate the SolidWorks data<br />Even Better Than Excel VBA? (Perhaps)<br />HERE<br />HERE<br />HERE<br />HERE<br />HERE<br />62<br />
    85. 85. What To Look For In A SolidWorks Solution Partner<br />How much programming do you want to do?<br />Rules can be expressed in VB.NET, Excel, Proprietary languages<br />Some allow programming to supplement the application<br />How do you want the users to interact?<br />Some run inside of SolidWorks (requires seats, some SW knowhow) <br />Do you need multiple people to specify a new unit simultaneously?<br />Some run inside of a SolidWorks model, and cannot do this<br />Some use SQL Server back ends to help support this<br />Where are the models going to be generated?<br />Server components free up your machine/require fewer SW seats<br />Do you want/need a Internet/intranet browser-based interface?<br />63<br />
    86. 86. Questions? Comments? Suggestions? Tamale Recipes?<br />If you have questions you would like to discuss, please find me<br />Now…At any time during the conference…or After the conference<br />Presentation available on www.razorleaf.com<br />Free newsletter with tech tips, industry insiders and more…<br />The <br />Sherpa<br />Paul Gimbel<br />Business Process Sherpa<br />Paul.Gimbel@razorleaf.com<br /> www.razorleaf.com<br />TheProcesSherpa on Twitter<br />
    87. 87. <ul><li>PLEASE PLEASEPLEASE fill out your survey
    88. 88. It takes practically no time at all
    89. 89. I HONESTLY want your feedback and I do apply it
    90. 90. Let’s see if the SolidWorks folks read these:</li></ul>SURVEY TIME!!!<br />PLEASE PLEASEPLEASE fill out your survey<br />It takes practically no time at all<br />I HONESTLY want your feedback and I do apply it<br />Let’s see if the SolidWorks folks read these:<br />In the comments section, write:<br />“A bicycle powered projector! <br />Very green. Very California.”<br />
    1. A particular slide catching your eye?

      Clipping is a handy way to collect important slides you want to go back to later.

    ×