62
Automating With Excel: An Object-Oriented Approach Paul Gimbel Razorleaf Corporation

Automating With Excel An Object Oriented Approach

Embed Size (px)

DESCRIPTION

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.

Citation preview

Page 1: Automating  With  Excel    An  Object  Oriented  Approach

Automating With Excel:An Object-Oriented ApproachPaul GimbelRazorleaf Corporation

Page 2: Automating  With  Excel    An  Object  Oriented  Approach

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 a Design Automation Strategy

• Questions and (if you’re lucky) Answers

Page 3: Automating  With  Excel    An  Object  Oriented  Approach

Not Sure If You Should Stay Here or Go See Lisa and Tammy’s “Migrating to ePDM”?

I’ve got:

• 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?

• And the overriding theme of What Is OOP (and how will it save me 15% or more on my car insurance)

(Lisa and Tammy are showing case studies of migrating data into ePDM without the use of custom code down in 201 A-B.)

Page 4: Automating  With  Excel    An  Object  Oriented  Approach

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 (eventually)

Download it from the Razorleaf Site (www.razorleaf.com)

Give me a business card and I’ll email it to you (the ppt, not your card)

Read the Presenter Notes!!

• Come on up after the session with any questions

• Follow me around the hallways until you can stop me

• Take my business card...take a few and hand them around

Page 5: Automating  With  Excel    An  Object  Oriented  Approach

Who Is This Guy and Where Did He Come From?

• Razorleaf Corporation SolidWorks Service Partner

Services ONLY (we’re not trying to sell you anything, we’re neutral)

Data Management (EPDM, SmarTeam, Aras)

Design Automation (DriveWorks, Tacton)

Workflow Automation (Microsoft SharePoint and Tools)

• Paul Gimbel (aka “The Sherpa”) 10+ years as Demo Jock, Applications Engineer, Trainer, Support Tech

5 years as Design Automation Implementer

Specializing in SolidWorks, DriveWorks, Tacton, Custom Programming

• (THERE! Now I can report this trip as reimbursable.)

The Sherpa

Page 6: Automating  With  Excel    An  Object  Oriented  Approach

“It’s All About The Process”

• Don’t just write a macro to push the same buttons, think bigger!

• Re-evaluate what SolidWorks can really do for you

• See the two previous (hidden) slides

Download the presentation and open it in PowerPoint

• See some of my previous SolidWorks World presentations (www.razorleaf.com)

Redesigning Processes for SolidWorks – SWW 2006

Lets Get Ready To Automate – SWW 2007

Automating Your Designs – SWW 2008

Using SolidWorks and API to Drive Complex Calculations – SWW 2009

Demystifying the SolidWorks API – SWW 2010

Automating Design Validation with the SolidWorks API – SWW 2010

Page 7: Automating  With  Excel    An  Object  Oriented  Approach

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

Page 8: Automating  With  Excel    An  Object  Oriented  Approach

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.

Page 9: Automating  With  Excel    An  Object  Oriented  Approach

Pure SolidWorks

• Configurations

• Design Tables

• Sensors

• Equations

• Smart Components

• Mate References

• Design Checker

• SolidWorks Task Scheduler

• DriveWorksXpress

• FeatureWorks

Page 10: Automating  With  Excel    An  Object  Oriented  Approach

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?

Page 11: Automating  With  Excel    An  Object  Oriented  Approach

SolidWorks Macros

• Designed to drive the SolidWorks User Interface

Not all that automation-friendly

• OK to use for small functions

• Can be tough to share due to peoples individual settings

• Often requires specific pre-selections

• Everything plays on the screen (video performance aspect)

Page 12: Automating  With  Excel    An  Object  Oriented  Approach

The Road To Excel

• Design Tables alone don’t address

User Interface (Configuration Manager, to a small extent)

Input values as opposed to output values

Advanced Excel functionality

• Leverage Excel Use Excel User Interface tools

Data validation

User Defined Functions

Macros

Add-Ins (Analysis Pack, Solver, etc.)

Page 13: Automating  With  Excel    An  Object  Oriented  Approach

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

Page 14: Automating  With  Excel    An  Object  Oriented  Approach

What Excel Brings To The Party (a six pack?)

•Formatting

•Charts

•Easy User Interfaces

•Advanced equation functionality

•VBA

Custom functions

Macros

Object-Oriented Programming (well, sort of)

Page 15: Automating  With  Excel    An  Object  Oriented  Approach

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

Page 16: Automating  With  Excel    An  Object  Oriented  Approach

Building User Interfaces in Excel

Data Validation– Lists, error and warning dialogs, tool tips

Input Messages

Error Messages

Warning Messages

In-Cell Dropdowns

Page 17: Automating  With  Excel    An  Object  Oriented  Approach

Building User Interfaces in Excel

Data Validation– Lists, error and warning dialogs, tool tips

Conditional Formatting– Control user’s attention based on input

Page 18: Automating  With  Excel    An  Object  Oriented  Approach

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

Page 19: Automating  With  Excel    An  Object  Oriented  Approach

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

Control Toolbox– VB-Style input device that can fill in your cells

Page 20: Automating  With  Excel    An  Object  Oriented  Approach

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

Page 21: Automating  With  Excel    An  Object  Oriented  Approach

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)

Page 22: Automating  With  Excel    An  Object  Oriented  Approach

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

Page 23: Automating  With  Excel    An  Object  Oriented  Approach

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”

Voltage Impedance

110 1.73

240 2.9

360 3.48

VLookup(110,VoltageRange,2,FALSE) = 1.73

VLookup(290,VoltageRange,2,FALSE) = N/A#

VLookup(359,VoltageRange,2,TRUE) = 2.9

Searches until it finds a value that is “greater than” the search value, then goes back to take the previous one.25

Page 24: Automating  With  Excel    An  Object  Oriented  Approach

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.250DGet(Holes,”Number”,Criteria2) = 2DGet(Holes,”Number”,Criteria3) = #NUM!DGet(Holes,”Dia”,Criteria4) = #VALUE!

26

Page 25: Automating  With  Excel    An  Object  Oriented  Approach

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

27

Page 26: Automating  With  Excel    An  Object  Oriented  Approach

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)

28

Page 27: Automating  With  Excel    An  Object  Oriented  Approach

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

29

Page 28: Automating  With  Excel    An  Object  Oriented  Approach

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)

30

Page 29: Automating  With  Excel    An  Object  Oriented  Approach

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.

31

Page 30: Automating  With  Excel    An  Object  Oriented  Approach

Custom Functions - Conversions• What about converting units or data types? (or both!)

Public Function FeetInches(TotalInches As Double) As String

Dim Feet As IntegerDim 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”32

Page 31: Automating  With  Excel    An  Object  Oriented  Approach

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 nth 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.33

Page 32: Automating  With  Excel    An  Object  Oriented  Approach

How To Program In VBA

The Ultimate Process For Non-Programmers:

1. Determine what you want your program/code snippet to do

2. Think of some “keywords” to describe it (if you know the functions you need to use, you’re ahead of the game)

3. http://www.google.com (add “VBA” and/or “Excel” to search)

4. Ctrl-C

5. Ctrl-V

6. Tweak

Also look to Excel VBA and SW API Help files. They’re actually helpful. I know! I was shocked, too.34

Page 33: Automating  With  Excel    An  Object  Oriented  Approach

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

35

Page 34: Automating  With  Excel    An  Object  Oriented  Approach

The Object Browser

36

Page 35: Automating  With  Excel    An  Object  Oriented  Approach

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

37

Page 36: Automating  With  Excel    An  Object  Oriented  Approach

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!

38

Page 37: Automating  With  Excel    An  Object  Oriented  Approach

Object-Oriented Programming**

“Everything you need to do in the SolidWorks API has to be done by or to an object.”

• Class – A definition (blueprint) of something (think: blank spec for a washer or bolt)

• Interface – A more generic definition incorporating multiple classes (ex. Hardware)

• Object – A specific instance of a class (completed spec - ex. 1/4-20 x 3 SHCS)

• Property – A parameter value that an object has (ex. Diameter)

• Method – Something (sub or function) that an object can do (ex. Install)

• Accessor – A method used to get an object (ex. GetFeature, GetChildren)

• Dot (.) –Separates an object from its property or method or “child” objects

Ex. Bolt.Length or Bolt.Thread.item(“Lead”).Pitch

• Instantiate – To make a real thing as defined by a class

Ex. Upper Flange Bolt #3 or Rear Axle Nut−Those are then called “instances” and “objects”

**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.

Page 38: Automating  With  Excel    An  Object  Oriented  Approach

The SolidWorks API Object Example (VBA)

Example: Creating a Hole Wizard Hole

Dim swApp As SldWorks.SldWorksDim swModel As SldWorks.ModelDoc2Dim swFeatMgr As SldWorks.FeatureManagerDim swFeat As SldWorks.FeatureDim swWzdHole As WizardHoleFeatureData2

Set swApp = Application.SldWorksSet swModel = swApp.ActiveDocSet swFeatMgr = swModel.FeatureManager…more code here…Set swWzdHole = swFeatMgr.CreateDefinition(swFmHoleWzd)swWzdHole.HoleDepth = 0.15swWzdHole.HoleDiameter = 0.0555…

Set swFeat = swFeatMgr.CreateFeature(swWzdHole)…more code here…

Early Bound Object Declarations aka “Fully Qualified” (+5 Style Points)

Object assignment (instantiation) requires the keyword Set in VBA only

HoleDepth and HoleDiameter are Properties of the WizardHoleFeatureData2 object

CreateDefinition and CreateFeature are Methods (functions)

Page 39: Automating  With  Excel    An  Object  Oriented  Approach

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

41

Page 40: Automating  With  Excel    An  Object  Oriented  Approach

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.)42

Page 41: Automating  With  Excel    An  Object  Oriented  Approach

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

43

Page 42: Automating  With  Excel    An  Object  Oriented  Approach

Option 2: Object-Oriented Approach

• Window Object has GlassPane objects

How many? An unlimited number!!!

Table can expand as much as it needs to

Each window has a Window object, an object that holds all of the GlassPanes

and an object for each GlassPane44

Page 43: Automating  With  Excel    An  Object  Oriented  Approach

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)

45

Page 44: Automating  With  Excel    An  Object  Oriented  Approach

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

46

Page 45: Automating  With  Excel    An  Object  Oriented  Approach

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

47

Page 46: Automating  With  Excel    An  Object  Oriented  Approach

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

48

Page 47: Automating  With  Excel    An  Object  Oriented  Approach

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

49

Page 48: Automating  With  Excel    An  Object  Oriented  Approach

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

50

Page 49: Automating  With  Excel    An  Object  Oriented  Approach

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.

*

51

Page 50: Automating  With  Excel    An  Object  Oriented  Approach

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

52

Page 51: Automating  With  Excel    An  Object  Oriented  Approach

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

53

Page 52: Automating  With  Excel    An  Object  Oriented  Approach

VERY Quick Lesson In Debugging

1. 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.

2. Use Breakpoints at each major stage to see where it trips

Click in this column to add a breakpoint

54

Page 53: Automating  With  Excel    An  Object  Oriented  Approach

VERY Quick Lesson In Debugging

1. 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.

2. Use Breakpoints at each major stage to see where it trips

3. Break at the last working area and Step (Shift+F8) through

4. If it trips in a function or subroutine, use F8 to step into it

5. Still can’t figure it out? Watch the values as you approach the problem spot by hovering over variables or “add watch”

55

Page 54: Automating  With  Excel    An  Object  Oriented  Approach

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.

56

Page 55: Automating  With  Excel    An  Object  Oriented  Approach

Connecting to SolidWorks

• Add the SolidWorks library to your project

Tools, Macros, Visual Basic Editor

Tools, References, SolidWorks 2010 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")

58

Page 56: Automating  With  Excel    An  Object  Oriented  Approach

Things To Note About SolidWorks API Programming

• Fairly well documented in the API Help File

• Macro Record, good start, but 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

• Check out my presentation yesterday at 1:30pm!! (www.razorleaf.com )

(Not enough time to go in depth into SolidWorks API programming, sorry)

59

Page 57: Automating  With  Excel    An  Object  Oriented  Approach

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)

60

Page 58: Automating  With  Excel    An  Object  Oriented  Approach

So What About VB.NET or C#?

• SolidWorks runs and even records VBA, VB.NET and C#.NET macros

• Microsoft Office…not so much (VBA to eternity and beyooooooond!)

• Mostly the same techniques as VBA

• OOP to the next level (although you really need to be good to see it)

• Slightly better performance

But SolidWorks is almost always the slowest link

• Extensible to the web ASP.NET

• Is everything moving towards .NET? Um, well, yeah, actually.

• Conversion from VBA to VB.NET? Pretty easy (C#, not so much)

• Learning .NET when you know VBA? Pretty easy (C#, not so much)

• Working in VBA when you know .NET? Pretty frustrating

• What about C#? More symbolic, more rigid, more professional and polished

61

Page 59: Automating  With  Excel    An  Object  Oriented  Approach

• 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

DriveWorks Ltd.Product Name: DriveWorks, DriveWorksSolo Tacton Systems ABProduct Name: TactonWorks ACATEC Software GmbHProduct Name: POWER CONFIGURATOR AlbianiProduct Name: iNorming CadWorks Software Oy LtdProduct Name: AutomateWorks® Citius CorporationProduct Name: KBMax Configure One, Inc.Product Name: Configure OneNuovamacutProduct Name: RPMWorks Power2, Inc.Product Name: power2design REITEC GmbHProduct Name: Confit Product ConfiguratorVEST, IncProduct Name: MDTools 900 Series VISIONKBEProduct Name: KBEWorks

Even Better Than Excel VBA? (Perhaps)

HERE

HERE

HERE

HERE

HERE

62

Page 60: Automating  With  Excel    An  Object  Oriented  Approach

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?

63

Page 61: Automating  With  Excel    An  Object  Oriented  Approach

Questions? Comments? Suggestions? Tamale Recipes?

• If you have questions you would like to discuss, please find me

Now…At any time during the conference…or After the conference

• Presentation available on www.razorleaf.com

Free newsletter with tech tips, industry insiders and more…

Paul GimbelBusiness

Process [email protected] www.razorleaf.com TheProcesSherpa on Twitter

The Sherpa

Page 62: Automating  With  Excel    An  Object  Oriented  Approach

• PLEASE PLEASE PLEASE fill out your survey

• It takes practically no time at all

• I HONESTLY want your feedback and I do apply it

• Let’s see if the SolidWorks folks read these:

SURVEY TIME!!!

• PLEASE PLEASE PLEASE fill out your survey

• It takes practically no time at all

• I HONESTLY want your feedback and I do apply it

• Let’s see if the SolidWorks folks read these:

In the comments section, write:“A bicycle powered projector! Very green. Very California.”