sww 2008 automating your designs excel, vba and beyond

61
Automating Your Designs Excel, VBA, and Beyond Paul Gimbel Razorleaf Corporation

Upload: razorleaf-corporation

Post on 19-Jan-2015

2.790 views

Category:

Technology


2 download

DESCRIPTION

This SolidWorks World 2008 presentation from Paul Gimbel of Razorleaf Corporation focuses on the use of Microsoft Excel as a tool to power SolidWorks design automation.

TRANSCRIPT

Page 1: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

Automating Your Designs

Excel, VBA, and Beyond

Paul GimbelRazorleaf Corporation

Page 2: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

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

Page 3: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

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)

Page 4: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

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

Page 5: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

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

Page 6: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

“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

Page 7: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

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: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

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: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

Pure SolidWorks

Configurations

Design Tables

Smart Components

Mate References

Design Checker

SolidWorks Task Scheduler

DriveWorksXpress

FeatureWorks

Page 10: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

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: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

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)

Page 12: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

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

Page 13: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

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: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

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 15: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

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: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

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: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

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: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

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: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

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

Page 20: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

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: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

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: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

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: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

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.

Page 24: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

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!

Page 25: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

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

Page 26: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

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 27: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

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

Page 28: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

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 thinkCylVolume = 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)

Page 29: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

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 = TrueElse

Divisible = FalseEnd 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.

Page 30: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

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”

Page 31: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

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.

Page 32: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

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.

Page 33: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

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

Page 34: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

The Object Browser

Page 35: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

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 rangeFor Each MyCell in Worksheets(“Calcs”).Range(“TestRange”)

Total = Total + MyCell.ValueNext 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 rowsFor Each MyRow in Worksheets(“Calcs”).Range(“TestRange”).Rows

Total = Total + MyRow.Cells(1,3).Value ‘Row 1, Column 3 of the rangeNext MyRow ‘Looping through the TestRange

Page 36: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

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!

Page 37: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

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”

Page 38: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

The SolidWorks API is Sort Of Object-Oriented

Example: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…Set swWzdHole = swFeatMgr.CreateDefinition(swFmHoleWzd)swWzdHole.HoleDepth = 0.15swWzdHole.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)

Page 39: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

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

Page 40: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

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

Page 41: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

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

Page 42: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

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 GlassPane

Page 43: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

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)

Page 44: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

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

Page 45: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

Defining a Class

Standard methods to put in:– Class_Initialize: Gets run each time this class is instantiatedPublic 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

Page 46: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

Collection Classes

Class_Initialize creates the collectionPrivate mcolGlassPanes As CollectionPrivate Sub Class_Initialize ()

Set mcolGlassPanes = New CollectionEnd Sub

AddPrivate Sub Add(uGlassPane As GlassPane)

mcolGlassPanes.Add uGlassPaneEnd Sub

RemovePrivate Sub Remove (ByVal varID As Variant)

mcolGlassPanes.remove varIDEnd Sub

You can pass this an index number or the value of the Name property

Page 47: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

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 GlassPanemGlassPane.Thickness = uThickness

mcolGlassPanes.Add mGlassPaneEnd Sub

Page 48: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

Collection Classes (Continued)

Item: allows you to refer to a single element of the collection

Public Function Item(ByVal varID As Variant) As GlassPaneSet item = mcolGlassPanes(varID)

End Function

Count: Returns the number of elements in the collectionPublic Get Count() As Long

Count = mcolGlassPanes.CountEnd Property

You can pass this an index number or the value of the Name property

Page 49: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

Ready? Set? … Instantiate!!

To add another panel (Using a nice User Interface)

Private Sub cmdAddPane_Click()

Dim iName As String ‘The input nameDim iType As String ‘The input typeDim iThk As Double ‘The input thickness

iName = Worksheets(“Input”).Range(“InputName”).ValueiType = Worksheets(“Input”).Range(“InputType”).ValueiThk = 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.

*

Page 50: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

Auto-Instantiation

Take a whole list of cell values and create the panes:

Dim cPanes As GlassPanesDim 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”).RowsiName = MyRow.Cells(1,1).ValueiThk = MyRow.Cells(1,2).ValueiType = MyRow.Cells(1,3).ValueiCoating = MyRow.Cells(1,4).ValuecPanes.Add iName, iThks, iType, iCoating

Next MyRow

Page 51: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

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

Page 52: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

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

Page 53: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

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”

Page 54: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

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.

Page 55: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

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")

Page 56: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

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)

Page 57: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

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)

Page 58: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

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

Page 59: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

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

Page 60: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

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?

Page 61: Sww 2008   Automating Your Designs   Excel, Vba And Beyond

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 GimbelBusiness Process

Sherpa

[email protected]

www.razorleaf.com