solidworks二次开发全教程系列之答禄夫天创作solidworks二次开发-01-录制一个宏第一步:我们需要自己录制一个宏,然后看看法式发生了什么代码.现在学习excel时候就是这么干的.只是,solidworks要复杂一些,直接录制的宏不能使用,需要做一些调整.在没有经验的时候我们最好依照下面的建议来做.Edit or Debug SolidWorks MacroEdit or debug SolidWorks macros using Microsoft VBA. 使用Microsoft VBA编纂或调试宏To edit or debug a SolidWorks macro:Click Edit Macro on the Macro toolbar, or click Tools, Macro, Edit.NOTES: 注意:To automatically edit a macro after recording it, click Tools, Options, Systems Options. On the General tab, select Automatically edit macro after recording and click OK. This setting is persistent across SolidWorks sessions.此选项Automatically edit macro after recording 顾名思义是在记录宏完毕后自动翻开编纂界面.If you recently edited the macro, you can select it from the menu when you click Tools, Macro. This menu lists the last nine macros that you edited.已经编纂了宏,菜单中会有最近的9个宏法式列表供选择.In the dialog box, select a macro file (.swp) and click Open. 选择一个宏swp文件NOTE: You can also edit .swb files, which are older-style SolidWorks macro files. When you run or edit a .swb file, it is automatically converted to a .swp file. 旧的宏文件后缀为swb,你也可以翻开swb,那么会自动保管为swp.Edit or debug the macro. If it is a new macro, be sure to:如果是新的宏Delete extra lines of code: 删除一些过剩的代码:The following variables are declared automatically in a SolidWorks macro. Delete any variables not used in the macro. 这些对象的声明是自动发生的,可以将没用的删除 Dim swApp As ObjectDim Part As ObjectDim boolstatus As BooleanDim longstatus As Long, longwarnings As LongDim FeatureData As ObjectDim Feature As ObjectDim Component As ObjectDelete all lines of code that change the view. 删除切换试图的代码译者注:像这样的Part.ActiveView().RotateAboutCenter 0.0662574, 0.0346621 无情的删失落吧Delete all ModelDocExtension::SelectByID2 calls appearing immediately before ModelDoc2::ClearSelection2 calls. However, do not delete ModelDocExtension::SelectByID2 calls appearing immediately after ModelDoc2::ClearSelection2 calls.Delete all ModelDoc2::ClearSelection2 calls appearing immediately before ModelDocExtension::SelectByID2. solidworks二次开发-02-用来访问特征的两个API来学习两个api:SelectByID2和GetSelectedObject5.这两个函数,第一个通过给出对象的name选择对象.第二个通过启用法式前已经选择的索引获得对象.看下面法式:Option ExplicitDim Model As ModelDoc2Dim feature As featureDim boolstatus As VariantSub main()' 选择叫"拉伸1"的特征boolstatus = Model.Extension.SelectByID2("拉伸1", "BODYFEATURE", 0, 0, 0, False, 0, Nothing,swSelectOptionDefault)'主要就是这一句话,在写Option Explicit后函数的最后一个参数swSelectOptionDefault可以使用0来取代' If the selection was successful, that is, "Extrude1" was' selected and it is a "BODYFEATURE", then get that feature; otherwise,' indicate failureIf boolstatus = True Then '如果有“拉伸1”这个特征下面的代码将其选中Dim SelMgr As SelectionMgrSet feature = SelMgr.GetSelectedObject5(1) '此处使用一个索引来获得特征ElseDebug.Print "Error"End IfEnd Sub最后列出这两个函数的VB语法:ModelDocExtension::SelectByID2DescriptionThis method selects the specified entity.Syntax (OLE Automation)retval = ModelDocExtension.SelectByID2 ( Name, Type, X, Y, Z, Append, Mark, Callout. SelectOption )Input:(BSTR) NameName of object to select or an empty stringInput:(BSTR) TypeType of object (uppercase) as defined in swSelectType_e or an empty stringInput:(double) XX selection location or 0Input:(double) YY selection location or 0Input:(double) ZZ selection location or 0Input:(VARIANT_BOOL) AppendIf...And if entity is...Then...TRUENot already selectedThe entity is appended to the current selection list Already selectedThe entity is removed from the current selection list FALSENot already selectedThe current selection list is cleared, and then the entity is put on the listAlready selectedThe current selection list remains the sameInput:(long) MarkValue that you want to use as a mark; this value is used by other functions that require ordered selectionInput:(LPCALLOUT) CalloutPointer to the associated calloutInput:(long) SelectOptionSelection option as defined in swSelectOption_e (see Remarks)Output:(VARIANT_BOOL) retvalTRUE if item was successfully selected, FALSE if not SelectionMgr::GetSelectedObject5DescriptionThis method gets the selected object.Syntax (OLE Automation)retval = SelectionMgr.GetSelectedObject5 ( AtIndex ) Input:(long) AtIndexIndex position within the current list of selected items, where AtIndex ranges from 1 to SelectionMgr::GetSelectedObjectCountOutput:(LPDISPATCH) retvalPointer to the Dispatch object as defined in swSelType_e; NULL may be returned if type is not supported or if nothing is selectedsolidworks二次开发-03-访问特征数据'coder arden'date :2005-03-22'used to get the simple hole infomation dep & dia'finished lucky !!'------------------------------------------------------------Option ExplicitDim Model As ModelDoc2Dim curfeature As featureDim boolstatus As BooleanDim featdata As SimpleHoleFeatureData2 '声明一个简单直孔对象Dim component As Component2Dim dep As DoubleDim dia As DoubleDim SelMgr As SelectionMgrDim ncount As IntegerSub getselected()Set curfeature = SelMgr.GetSelectedObject5(1) '获得以后选中的第一个特征Set featdata = curfeature.GetDefinition '获得特征的界说boolstatus = featdata.AccessSelections(Model, component) ' 可以对数据进行访问了ncount = featdata.GetFeatureScopeBodiesCount MsgBox ncountdep = featdata.DepthMsgBox dia & "*" & dep'MsgBox "error arden" '在solidworks中可以使用swAPP.sendmsgtouser2End Sub**********************************************上面法式运行前,假设你选择了一个简单直孔特征.然后获得这个孔德一些参数.孔深、直径等.solidworks的API虽然是e文的.介绍的还算详细,而且有很多的example.年夜家可以多看看代码.要访问一个特征,需要经历这样的步伐:界说一个特征对象: dim....as ...获得这个特征:比如使用GetSelectedObject5 还有SelectebyID等...获得界说:GetDefinition进行访问:AccessSelections上面的法式没有if选择的容错机制,需要添加上.solidworks二次开发-04-修改数据上次已经可以访问特征的各参数了,今天我们来修改它:要修改前面的步伐不能少,当我们已经可以读取一些特征时,我们就可以给他设定一些值.固然有时需要调用特定的参数.solidworks是ole和com的,所以要习惯这样.在修改完特征后需要调用函数modifydefinition()来实现变动.我们给一个例子,这个例子比前面的都要全面,它有很好的容错引导机制,可以直接拿来成为一个稳定的宏法式.Dim Model As ModelDoc2Dim Component As Component2Dim CurFeature As featureDim isGood As Boolean' Will become an ExtrudeFeatureData ObjectDim FeatData As ObjectDim Depth As DoubleDim SelMgr As SelectionMgrSub doubleBE()}}--> }}-->Set swApp = CreateObject("sldWorks.application")}}--> }}-->' Make sure that the active document is a part}}--> }}-->If Model.GetType <> swDocPART And Model.GetType <> swDocASSEMBLY Then‘这里的swDocPART 、swDocASSEMBLY 我的环境没有通过.我使用msgbox Model.GetType 的笨法子获得整数为1和2}}--> }}-->Msg = "Only Allowed on Parts or Assemblies" ' Define message}}--> }}-->Style = vbOKOnly ' OK Button only}}--> }}-->Title = "Error" ' Define title}}--> }}-->Call MsgBox(Msg, Style, Title) ' Display error message}}--> }}-->Exit Sub ' Exit this program}}--> }}-->End If}}-->}}-->}}--> }}-->' Get the Selection Manager}}-->}}-->}}--> }}-->' Get the selected object (first in the group if there are more than one)}}--> }}-->' Note that at this point CurFeature is just a Feature Object}}--> }}-->Set CurFeature =SelMgr.GetSelectedObject3(1)}}--> }}-->If CurFeature Is Nothing Then}}--> }}-->' Tell the user that nothing is selected}}--> }}-->swApp.SendMsgToUser2 "Please select the Base-Extrude", swMbWarning, swMbOk}}--> }}-->Exit Sub}}--> }}-->End If}}--> }}-->' Check the feature's type name}}--> }}-->' Make sure it is an extrusion}}--> }}-->If Not CurFeature.GetTypeName = swTnExtrusion Then’在这里使用swTnExtrusion我的环境没有通过,我改成了Extrusion才ok}}--> }}-->swApp.SendMsgToUser2 "Please select the Base-Extrude", swMbWarning, swMbOk}}--> }}-->Exit Sub}}--> }}-->End If}}--> }}-->' Get the Extrusion's Feature Data}}-->}}-->}}--> }}-->' Get the access selections for the feature data}}--> }}-->' Note that Component is NULL when accessing the selections of a standalone part. }}--> }}-->If we were calling AccessSelections from within an assembly, then model would refer to the top-level document in the assembly and component would refer to the actual part.}}--> }}-->isGood = FeatData.AccessSelections(Model, Component)}}-->}}-->}}--> }}-->' Inform the user of an error}}--> }}-->If Not isGood Then}}--> }}-->swApp.SendMsgToUser2 "Unable to obtain access selections", swMbWarning, swMbOk}}--> }}-->Exit Sub}}--> }}-->End If}}-->}}-->}}--> }}-->' Make sure the user has selected the base extrude}}--> }}-->If Not FeatData.IsBaseExtrude Then}}--> }}-->swApp.SendMsgToUser2 "Please select the Base-Extrude", swMbWarning, swMbOk}}--> }}-->Exit Sub}}--> }}-->End If}}-->}}-->}}--> }}-->' Change the depth of this extrusion to double its previous depth}}--> }}-->Depth = FeatData.GetDepth(True)}}--> }}-->FeatData.SetDepth True, Depth * 2}}-->}}-->}}--> }}-->' Implement the changes to the feature}}--> }}-->isGood = CurFeature.ModifyDefinition(FeatData, Model, Component) }}-->}}-->}}--> }}-->' If the modify definition failed}}--> }}-->If Not isGood Then}}--> }}-->swApp.SendMsgToUser2 "Unable to modify feature data", swMbWarning, swMbOk}}--> }}-->' Release the AccessSelections}}--> }}-->End If}}-->}}-->End Sub如果呈现特征呈现“退回”状态,我现在还没有找到问题的原因,只能在代码执行到最后调用Model.Rebuild这两个函数来自动更新.Solidworks二次开发---05--装配体中拔出零部件在往装配体中拔出零部件时,我们使用addcomponent 函数.如果需要选定零部件的配置,则需要使用addcomponent4.先学习下语法:addcomponent4:retval = AssemblyDoc.AddComponent4 ( compName, configName,x, y, z)Input: (BSTR) compName Pathname of a loaded part or assembly to add as a componentInput: (BSTR) configName Nameof the configuration from which to load the componentInput: (double) x X coordinate of the component centerInput: (double) y Y coordinate of the component centerInput: (double) z Z coordinate of the component centerOutput: (LPCOMPONENT2) retval Pointer to theComponent2 object需要注意的是:参数1为文件的全名(包括路径);参数2为文件的配置名称;当函数执行胜利购返回一个指向该零件的指针.于是我们可以如下写一个小法式,用来给装配体中插零件:‘‘write byarden2005-4-4‘this function add a part called “”in CurrentWorkingDirectory‘precondition is there has a part document called “”in CurrentWorkingDirectory‘and it has a configuration called “配置1”Dim Model As ModelDoc2Dim pth As StringDim strpath As StringSub insertPart()strpath = swApp.GetCurrentWorkingDirectory ‘以后工作路径pth = strpath & "零件 1.SLDPRT" ‘获得文件的FULLPATH全名Model.AddComponent4 pth, "配置1", 0, 0, 0 ‘添加零部件End Sub然而,这个法式比不是想象中那么好用.为什么呢??回头看addcomponent4的remark,上面这样写:The specified file must be loaded in memory. A file isloaded into memory when you load the file in yourSolidWorks session (SldWorks::OpenDoc6) or open anassembly that already contains the file.就是说你想指定的拔出的文件必需在调用函数之前已经在内存中加载了.不习惯,你就不能直接翻开多简单,没法子,我还没有找到好的方法,只能按人家的来:看看下面的函数Opendoc6,它翻开一个文档:Opendoc6:retval = SldWorks.OpenDoc6 ( filename, type, options, configuration, &Errors, &Warnings )Input: (BSTR) Filename Document name or full path if not in current directory,including extensionInput: (long) Type Document type as defined in swDocumentTypes_eInput: (long) Options Mode in which to open the document as defined in swOpenDocOptions_eInput: (BSTR) Configuration Model configuration in which to open this document:Applies to parts and assemblies, not drawingsIf this argument is empty or the specified configurationis not present in the model,the model is opened in the last-used configuration.Output: (long) Errors Load errors as defined in swFileLoadError_eOutput: (long) Warnings Warnings or extra information generated during the openoperation as defined in swFileLoadWarning_eReturn: (LPDISPATCH) retval Pointerto a Dispatch object, the newly loaded ModelDoc2, or NULLif failed to open这个函数参数1就是文档的全名,参数2是要拔出的类型描述,其中0123分别暗示:0 swDocNONE:不是sw文件1 swDocPART:零件2 swDocASSEMBLY:装配体3 swDocDRAWING:工程图如果想使用swDocNONE,需要界说:Public Enum swDocumentTypes_e}--> }-->swDocNONE = 0}--> }-->swDocPART= 1}--> }-->swDocASSEMBLY = 2swDocDRAWING=3End Enum参数3是翻开文档的模式,一般我们就选择swOpenDocOptions_Silent 用0 暗示,固然还有只读、只看等选项参数4是翻开选项,一般置空后面是两个OutPut,用来显示毛病翻开时的提示函数返回一个指向翻开文件的指针.依照上面的要求我们在向装配体中拔出一个零部件时,需要这样步伐:1、获得装配体2、使用opendoc6翻开需要拔出的零件3、使用addcomponent4拔出零件到装配体我们上面的法式需要这样来修改一下,添加了一个翻开文档的函数:'******************************************************************************' insertpart 03/21/05 byarden'拔出零件1'前提条件:在装配体所在文件夹中有零件“零件1”存在,而且零件1有配置“配置1”'********************************************************* *********************Dim Model As ModelDoc2Dim YSBmodel As ModelDoc2Dim pth As StringDim strpath As StringDim nErrors As LongDim nWarnings As LongSub insertpart()pth = strpath & "零件1.SLDPRT"openYSB (pth) ‘在添加零部件之前,先翻开它Model.AddComponent4 pth, "配置1", 0, 0, 0End Sub'这个函数翻开零件1Sub openpart(ByVal pth As String)Dim path As Stringpath = pthSet YSBmodel = newswapp.OpenDoc6(path, 1, swOpenDocOPtions_Silent, "", nErrors, nWarnings) YSBmodel.Visible = False ‘我不想看到零件1End Sub回复引用陈说道具 TOPSolidworks二次开发—06—在装配体中添加配合折腾了三天终于完成了计划中的功能模块.在一个装配体中自动判断拔出合适的零件,并添加配合.在前面几篇文章中我已经基本上说明了如何获得零部件的数据信息、如何拔出零部件、如何获得已经选择的特征等.下面只介绍怎样进行配合在做配合时,需要经常选择到零件的面、线等,这是一个问题,还有就是介绍一下addmate2函数的使用:一般进行配合我们依照下面的次第来进行:1-ModelDoc.ClearSelection2 ‘取消所有选择2-选择需要配合的实体(entity)3-使用AddMate2函数进行配合4-再次使用 ModelDoc.ClearSelection2 ‘取消所有选择主要的问题在于如何选择合适的面:由于面的命名没有什么规律,很多时候是法式自动来命名的,这样,不方便使用selectbyID来选择,我也不想使用坐标值来选择一个面,那样做更加糟糕.在获得一个组件(component)或者一个特征(feature)时,我们有getfaces、getfirstface、getnextface等方法,我们可以使用这些方法遍历一个组件或特征等的各个面,来到达选择面的目的,看下面法式:Private Function selectface(dcom As ponent2,tp As Integer) As BooleanSet swdowelbody = dcom.GetBody()If swdowelbody Is Nothing Then '毛病处置MsgBox "选择零件失败"selectface = FalseExit FunctionEnd IfSet swDCface = swdowelbody.GetFirstFace ‘获得第一个面Do While Not swDCface Is Nothing ‘遍历各个面Set swDsurface = swDCface.GetSurface ‘获得概况对象If swDsurface.IsCylinder Then ‘如果是圆柱面If tp = 0 Then 'means cylinderSet swDEnt = swDCfaceswDEnt.Select4 True, selDdataselectface = TrueExit FunctionEnd IfElse ‘如果是其它,固然实际中我们可能需要使用select来界说好多分支If tp = 1 Then 'means planeSet swDEnt = swDCfaceswDEnt.Select4 True, selDdataselectface = TrueExit FunctionEnd IfEnd IfSet swDCface = swDCface.GetNextFaceLoopEnd Function此函数接受两个参数,第一个是一个component对象,第二个用来标识选择类型:0暗示圆柱面,1暗示平面.此函数运行完成后将选择指定组件的指定类型的一个面.需要注意的是我们需要在判断面类型时候需要转换到surface对象.而且选择需要界说一个entity对象,用来select4,到达选择的目的.可能这个过程有些复杂,年夜家依照这个顺序多测试几次,就明白了它的工作原理.上面的函数写的其实欠好,是我从我的工程中截取的一段.下面介绍一下addmate2函数:Syntax (OLE Automation) OLE语法:pMateObjOut = AssemblyDoc.AddMate2 ( mateTypeFromEnum, alignFromEnum, flip, distance, distAbsUpperLimit, distAbsLowerLimit, gearRatioNumerator, gearRatioDenominator, angle, angleAbsUpperLimit, angleAbsLowerLimit, errorStatus )参数:Input:(long) mateTypeFromEnumType of mate as defined in swMateType_e配合类型Input:(long) alignFromEnumType of alignment as defined in swMateAlign_e对齐选项Input:(VARIANT_BOOL) flipTRUE to flip the component, FALSE otherwise是否翻转Input:(double) distanceDistance value to use with distance or limit mates 距离Input:(double) distAbsUpperLimitAbsolute maximum distance value (see Remarks)距离限制maxInput:(double) distAbsLowerLimitAbsolute minimum distance value (see Remarks)距离限制minInput:(double) gearRatioNumeratorGear ratio numerator value for gear mates齿轮配合分子值Input:(double) gearRatioDenominatorGear ratio denominator value for gear mates齿轮配合分母值Input:(double) angleAngle value to use with angle mates角度Input:(double) angleAbsUpperLimitAbsolute maximum angle value角度限制maxInput:(double) angleAbsLowerLimitAbsolute minimum angle value角度限制minOutput:(long) errorStatusSuccess or error as defined by swAddMateError_e毛病陈说Return:(LPMATE2) pMateObjOutPointer to the Mate2 object返回指向配合的指针RemarksTo specify a distance mate without limits, set the distAbsUpperLimit and distAbsLowerLimit arguments equal to the distance argument's value.指定一个没有限制的距离,设定距离限制的最年夜、最小值和距离值相等If mateTypeFromEnum is swMateDISTANCE or swMateANGLE when the mate is applied to the closest position that meets the mate condition specified by distance or angle, then setting flip to TRUE moves the assembly to the other possible mate position.如果是距离或角度配合,配合将从符合条件的最近端进行配合,我们可以设定flip为true,改变配合至另一个合适的位置Use:使用配合的步伐ModelDoc2::ClearSelection2(VARIANT_TRUE) before selecting entities to mate.ModelDocExtension::SelectByID2 with Mark = 1 to select entities to mate.ModelDoc2::ClearSelection2(VARIANT_TRUE) after the mate is created.If mateTypeFromEnum is swMateCAMFOLLOWER, then use a selection mark of 8 for the cam-follower face.如果配合类型为凸轮,在概况标示8. 注:这个我也不太明白哈哈If nothing is preselected, then errorStatus is swAddMateError_IncorrectSeletions and pMateObjOut is NULL/Nothing.如果实现没有限定实体来配合,将会抱错swAddMateError_IncorrectSeletions,函数返回NULL或者Nothing上面就是API帮手所说的话,下面给出一段示例法式,假设之前我们已经选择了两个半径一样的圆柱面,那么我们来界说一个同心配合:Set swmatefeat = swassy.AddMate2(1, 0, False, 0, 0, 0, 0, 0, 0, 0, 0, nErrors)其中的 Dim swassy As SldWorks.AssemblyDocDim swmatefeat As Object注:在编程中有时候不能实现确定一个对象的类型,我们可以声明一个Object对象,让VB自己去匹配.但这样做是影响了效率.要完成一个距离或者角度要麻烦一些,就像上面的remark中说明的:Set swmatefeat = swassy.AddMate2(5, 1, True, 0.001, 0.001, 0.001, 0, 0, 0, 0, 0, nErrors)在这里我们需要将min和max都设置成与距离值相等,要否则配合会认为我们设定了高级配合中的限制条件,会报错.而且第三个参数和第二个参数需要按实际情况来确定.最后我们列出AddMate2的类型:swMateType_e‘Specifies values for assembly-mate information. swMateCOINCIDENT 0 重合swMateCONCENTRIC 1 同心swMatePERPENDICULAR 2 垂直swMatePARALLEL 3 平行swMateTANGENT 4 相切swMateDISTANCE 5 距离swMateANGLE 6 角度swMateUNKNOWN 7 未知swMateSYMMETRIC 8 对称swMateCAMFOLLOWER 9 凸轮swMateGEAR 10 齿轮回复引用陈说道具 TOPSolidworks二次开发—07—控制草图对象Get All Elements of Sketch Example (VB)Solidwork中对草图的控制,下面的例子很详细.特征下的草图在solidwork中其实是特征的子特征,我们可以对特征进行GetFirstSubFeature、及GetNextSubFeature获得.如果有需要年夜家可以从中找到对直线、弧线、圆等对象的把持.代码是solidworks的示例文件,里面充满了debug.print,只是向用户显示法式执行的结果.This example shows how to get all of the elements of a sketch.'---------------------------------------------' Preconditions: Model document is open and a sketch is selected.' Postconditions: None'---------------------------------------------。