1、VBA in DPWith excerpt from How to Think Like a Computer Scientistby Jeffrey Elkner,Allen B.Downey,and Chris MeyersThings to Consider in ProgrammingVBA in DPProgramming for Designers Let computer to do mundane work and save time/resources Generate(parametric)designs with lots of variations New way of
2、 design,or construction:Looks cool,may earn more?Time to think in a different way Formulate problems Goal Input/Output Driving/Driven Think creatively about solutions Methodology Procedure Represent a solution clearly and accurately Diagram DictationProgramming Language Natural language What people
3、speak English,French,Korean,Formal language Designed for specific applications Mathematical formula,Chemical structure Programming language,of courseVBA Visual Basic for Application VB for Application Integrated into host application Automate processes Visual Basic High level programming language de
4、signed to be learned and used easily One of the programming languages for DP CAT Script,VBA,.NET,VBA is included in a standard DP installationVBA Visual Basic for Application Interpreter CompilerProgram A sequence of instructions specifying computations Instructions Input Output Math Conditional exe
5、cution RepetitionDebugging Fixing errors Errors Syntax error Runtime error Semantic errorGlossary Algorithm A general process for solving a category of problems Exception Another name for a runtime error Script A program stored in a file(usually one that will be interpreted)Variables,Expressions and
6、 StatementsVBA in DPValue and Data Types Value Letter,number,Abc,aaa,1,2,3,Data types String,Integer,Double,Variables A name that refers to a value Variable names aa=1 bb=“names”Keyword and,if,for,while,sub,function,.Statements Statement is a complete instruction that can contain keywords,operators,
7、variables,constants,and expressions.Operators:+,-,*,/,Constant:fixed(constant)variableSet partDocument1=CATIA.ActiveDocument Declaration statements name a variable,constant,or procedure and can also specify a data typeDim partDocument1 As PartDocument Executable statements initiate actionsselect1.Se
8、arch(name=Optimization.MinimumValue,all)FunctionsVBA in DPFunction A named sequence of statements that performs a desired operation.This operation is specified in a function definitionSub mySubName()MsgBox HelloEnd SubSub mySubwithParameter(myParameter)MsgBox myParameterEnd SubSub/Function Sub No re
9、turn value Function With a return valueSub mySubName()MsgBox HelloEnd SubFunction myFunction()myFunction=HiEnd SubSub callFunction()Msgbox myFunctionEnd SubConditional ExecutionVBA in DPConditional Execution Doing different computations depending on(boolean)conditionsIf Then(ElseIf Then.)(Else)End i
10、fSelect Case Case Case Else End SelectBoolean condition A numeric expression or string expression that evaluates to True or False Comparison Operators Used to compare expressions.,=,=,Var1 Var2 And,Or,Not,Xor OperatorVar1 Var3IF Then Else Statement If condition Then statements Else elsestatements Or
11、,you can use the block form syntax:If condition Then statements ElseIf condition-n Then elseifstatements.Else elsestatements End If If A 10 Then A=A-10ElseIf A 10 ThenA=A+10ElseA=0End IfSelect Case Statement Select Case testexpression Case expressionlist-n statements-n.Case Else elsestatements-n End
12、 Select Dim Color,MyVarSub ChangeBackground(Color)MyVar=lcase(Color)Select Case MyVar Case red document.bgColor=red Case green document.bgColor=green Case blue document.bgColor=blue Case Else MsgBox pick another color End SelectEnd SubIterationVBA in DPIteration A repetition of a process For Next Fo
13、r Each Next Do Loop While.WendFor Nextj=0For i=0 to 10j =j+iNextMsgBox The J is&j For i=0 to 10 Step 2j =j+iNextMsgBox The J is now&j For.Next Statement For counter=start To end Step step statements Exit For statements Next For I=1 To 10 For J=1 To 10 For K=1 To 10 .Next NextNextWhile WendCounter=0W
14、hile Counter 10Counter=Counter+1WendMsgBox“Counter is now“&CounterDo.Loop Statement Do While|Until condition statements Exit Do statements LoopDo statements Exit Do statements Loop While|Until condition Do.Loop StatementDo Until DefResp=vbNo MyNum=Int(6*Rnd+1)Generate a random integer between 1 and
15、6.DefResp=MsgBox(MyNum&Do you want another number?,vbYesNo)LoopDim Check,CounterCheck=True:Counter=0 Initialize variables.Do Outer loop.Do While Counter 20 Inner loop.Counter=Counter+1 Increment Counter.If Counter=10 Then If condition is True.Check=False set value of flag to False.Exit Do Exit inner
16、 loop.End If LoopLoop Until Check=False Exit outer loop immediately.ArrayDim students(6)As Integer Object Oriented ProgrammingVBA in DPObject Oriented Programming OOP is all about programming using something called an object OOP consists of designing a bunch of classes most of which will be used as
17、templates to make objects The objects will be used to hold data and will be initialized with constructors and perform useful functions by being asked to run their methodsFrom CS1322 lecture slideWhat is an object?A chunk of memory which contains some data and methods which can operate on the data.So
18、mething that when created may have had special code run to initialize it.Something which has additional behavior defined by methods which can Be passed data via parameters Perform calculations/operations which may Change some of its data Perform some desired operation Return the value of some of its
19、 data Return the results of calculations using both data passed in and data contained in the objectFrom CS1322 lecture slideHow do we define different types of objects?For each different type of object we write a class.New classes may be based on existing classes to allow code reuse A class serves a
20、s a blueprint or template defining how all objects made from this class operate and what data they hold.One class may be used to make one or many objectsFrom CS1322 lecture slideClass:It describes the form of an object.It is a template or blueprint.It specifies data representation,behavior,and inher
21、itance(via variables,methods and parents)Object:It is an instance of a class.It has a unique copy of every non-static variable.(i.e.,the “instance variables”but not the class variables(those labeled with“static”).Naming Conventions:Classes:Identifiers begin with cap letters for each word in the iden
22、tifier,e.g.,class GraduateStudentObjects:Identifiers begins with lower case letter,then caps for other words in identifier,e.g.,graduateStudentPresident Difference between“a class and an object of that class”is analogous to the difference between“a type and a variable of that type”.Key IdeaClasses a
23、nd ObjectsFrom CS1322 lecture slide3 key features Abstract data types Encapsulation of data and behavior Classes as templates used to produce 1 or more instances or objects Inheritance Provides for code-reuse Polymorphism/Dynamic Binding Different objects in the same family may have identically name
24、d methods The language takes care of sorting out the correct method to invoke for usFrom CS1322 lecture slideClass Template for an object.Class.End Class construct Variable Properties Method EventClass Construct Class.End Class Class classnameClass definition End Class Instantiation an object of a c
25、lass Set objc=new classnameClass Variables Class has variables Dim varName1,varName2.Private varName1,varName2.Public varName1,varName2.Dim,Public Open to outside Private Closed to outsideClass Properties Access“wrapper”for private variables Property Get Property Let:value Property Set:referenceClas
26、s PropertiesClass ComputerPrivate modStrType Private oOS Public Property Let ComputerType(strType)modStrType=strType End Property Public Property Get ComputerType()ComputerType=modStrType End Property Public Property Set OperatingSystem(oObj)Set oOS=oObj End Property Public Property Get OperatingSys
27、tem()Set OperatingSystem=oOS End PropertyEnd ClassClass Method Functions or subroutines in a classClass LaptopComputerPrivate modOwnerPublic Property Let CompOwner(strOwner)modOwner=strOwnerEnd PropertyPublic Property Get CompOwner()CompOwner=modOwnerEnd PropertyPublic Function GetOwner()GetOwner=mo
28、dOwnerEnd FunctionEnd ClassClass Event Two events are automatically associated with every class you create Class_Initialize is fired whenever you instantiate an object based on this class Class_Terminate is called when the script engine determines that there are no remaining references on an objectC
29、lasses in the codeDim documents1 As DocumentsSet documents1=CATIA.DocumentsDim partDocument1 As PartDocumentSet partDocument1=documents1.Add(Part)PropertyMethodSet Statement Assigns an object reference to a variable or property.Set documents1=CATIA.DocumentsSet Statement You must use Set only if the
30、 returned value is an object,but not if it is a character string or a number.Nevertheless,character string and number defined as CATIA literals are objects and Set must be used if a Function returns a literal object.Finally,you dont have to use Set if you store your return value in a Property:myObje
31、ct.aggregatedObject=Object.Function(arg1,arg2,arg3)because there is no actual aggregatedObject variable,a property is a syntactical shortcut for accessor methods,here get_aggregatedObject and set_aggregatedObject,allowing to present those methods as an attribute of the object.The previous syntax is
32、so equivalent to:myObject.set_aggregatedObject(Object.Function(arg1,arg2,arg3)and no Set is required.Classes in DPVBA in DPDigital Project Classes Application Documents PartDocuments Part HybridShapeFactory HybridBodies HybridBody Referecence.And moreSub CATMain()Dim documents1 As DocumentsSet docum
33、ents1=CATIA.DocumentsDim partDocument1 As PartDocumentSet partDocument1=documents1.Add(Part)Dim part1 As PartSet part1=partDocument1.PartDim hybridShapeFactory1 As HybridShapeFactorySet hybridShapeFactory1=part1.HybridShapeFactoryDim hybridShapePointCoord1 As HybridShapePointCoordSet hybridShapePoin
34、tCoord1=hybridShapeFactory1.AddNewPointCoord(100#,100#,100#)Application The root object for all CATIA macros is Application.This corresponds to the CATIA frame window.The CATIA application is always named CATIA for in-process access,and you should only refer to it since it already exists when you ru
35、n an in-process macro.Dim documents1 As DocumentsSet documents1=CATIA.DocumentsDocuments Object A Collection of Document objects.Dim documents1 As DocumentsSet documents1=CATIA.DocumentsPartDocument Role:When a PartDocument object is created,a Part object is also created.This Part object is the root
36、 object of the Part structure.A reference Product object is also created in each PartDocument.It is used to access Publications,PartNumber.Dim partDocument1 As PartDocumentSet partDocument1=documents1.Add(Part)Part The root level object inside a PartDocument object.Role:It aggregates all the objects
37、 making up the part document.It provides many factories and collections.The collections list only the direct children of the part.Selection.Search allows to get all objects of one type.Dim part1 As PartSet part1=partDocument1.PartHybridShapeFactory Interface to create all kinds of HybridShape object
38、s that may be needed in wireframe and surface design.Dim hybridShapeFactory1 As HybridShapeFactorySet hybridShapeFactory1=part1.HybridShapeFactoryHybridShapePointCoord Point defined by coordinates.Role:To access data of the point feature created with its cartesian coordinates.Dim hybridShapePointCoo
39、rd1 As HybridShapePointCoordSet hybridShapePointCoord1=hybridShapeFactory1.AddNewPointCoord(100#,100#,100#)AxisSystems A collection of all the AxisSystem objects contained in the part.Dim axisSystems1 As AxisSystemsSet axisSystems1=part1.AxisSystemsAxisSystem The object Axis System A axis system has
40、 got one origin point and three orthogonal axes,crossing at the origin point.Dim axisSystem1 As AxisSystemSet axisSystem1=axisSystems1.Item(Absolute Axis System)Reference Represents an object pointing to another object.This other object can be either a wireframe GeometricElement object such as a pla
41、ne or a line,or a boundary representation object such as a face,a vertex or an edge.It may be,in particular,a Boundary object.References are created using appropriate methods for parts.They are then passed to an object to enable associativity with the referenced object.Dim reference1 As ReferenceSet
42、 reference1=part1.CreateReferenceFromObject(axisSystem1)Dim reference2 As ReferenceSet reference2=part1.CreateReferenceFromObject(hybridShapePointCoord1)HybridBodies A collection of the HybridBody objects.Dim hybridBodies1 As HybridBodiesSet hybridBodies1=part1.HybridBodiesHybridBody The object is a
43、 hybrid body.The hybrid body manages a set of geometric elements,a set of hybrid shapes,a set of bodies and a set of hybrid bodies.It belongs to the HybridBodies collection of a Part or ref CATIABody or HybridBody object.Dim hybridBody1 As HybridBodySet hybridBody1=hybridBodies1.Item(Geometrical Set
44、.1)HybridBody.AppendHybridShape Appends a hybrid shape to the hybrid body.Parameters:iHybriShape The hybrid shape to append.Example:This example appends the hybrid shape hybridShape to the hybrid body hybridBody:hybridBody.AppendHybridShape hybridShape hybridBody1.AppendHybridShape hybridShapePointC
45、oord1hybridBody1.AppendHybridShape hybridShapeLinePtDir1Sample programVBA in DPWorkflow in writing code in DP VBA Think about the process of generating the shape Use macro recording to get sample code Set user inputs Clean up unnecessary code Modify the sample code with VB statements Debug Add Dialo
46、g box for better UI Add more additional functionsFor.Next Statement For counter=start To end Step step statements Exit For statements Next For I=1 To 10 For J=1 To 10 For K=1 To 10 .Next NextNextWorkflow in creating a surface Create control points Location of points Distance between points Number of
47、 points Create control curves Distance between curves Number of curves Create surfaceDocument GenerationGenerating pointComment outAdding hybridbody(gemetrical set)Adding splineAdding surfaceUser inputs as variablesConversion of adding points Number of points needed Number of points*number of curves
48、 Use two loops One for points One for curves For Next Where to keep generated points?Create new geometrical set and keep points for one curveAdding new hybridbodySet initial values for variablesDebuggingStop DebuggingAdding new hybridBodyFunction for changing nameStr FunctionReturns a Variant(String
49、)representation of a number.Len FunctionReturns a Long containing the number of characters in a string or the number of bytes required to store a variable.-1:because of O at the end of string in DP VBA(?)Declaring variables for pointDirection of curves:Y axisDirection of array of curves:X axisX,Y va
50、luesZ value with Rnd(random)valueClean up codes for other pointsAdd two loops for curvesAdjust existing code for curve gen MovedMovedComment out or deleteComment out or deleteAdding created pointChange this one into proper pointAccessing created pointsTemporary variable declaration for pointsAccessi
侵权处理QQ:3464097650--上传资料QQ:3464097650
【声明】本站为“文档C2C交易模式”,即用户上传的文档直接卖给(下载)用户,本站只是网络空间服务平台,本站所有原创文档下载所得归上传人所有,如您发现上传作品侵犯了您的版权,请立刻联系我们并提供证据,我们将在3个工作日内予以改正。