使用SOLIDWORKS API:替换组件的实战操作

替换所选择的组件

此宏允许使用 SOLIDWORKS API 将树中的选定组件替换为指定文件夹中的组件(可选名称中的附加后缀)。

这在管理类似类型的项目时可能很有用,在这些项目中,某些文件被复制、更新和重命名,并且需要在原始程序集中替换。

此宏仅使用 API 选择,允许保留原始选定的组件,并避免需要使用临时集合变量来满足 IAssemblyDoc::ReplaceComponents2 SOLIDWORKS API 方法的要求,其中需要选择每个组件进行替换。

  • 修改输入参数。通过文件名的REPLACEMENT_DIR和可选后缀设置更换部件所在的目录。
Const REPLACEMENT_DIR As String = "D:\Assembly\Replacement"
Const SUFFIX As String = "_new"
  • 选择组件。
  • 运行宏。更换所有组件。
Const REPLACEMENT_DIR As String = "D:\Assembly\Replacement"
Const SUFFIX As String = "_new"

Dim swApp As SldWorks.SldWorks
Sub main()
    Set swApp = Application.SldWorks
    Dim swModel As SldWorks.ModelDoc2
    Set swModel = swApp.ActiveDoc
    If Not swModel Is Nothing Then
        Dim swAssy As SldWorks.AssemblyDoc
        Set swAssy = swModel
        Dim swSelMgr As SldWorks.SelectionMgr
        Set swSelMgr = swModel.SelectionManager
        Dim i As Integer
        For i = 1 To swSelMgr.GetSelectedObjectCount2(-1)
            If swSelMgr.GetSelectedObjectType3(i, -1) = swSelectType_e.swSelCOMPONENTS Then
                Dim swComp As SldWorks.Component2
                Set swComp = swSelMgr.GetSelectedObject6(i, -1)
                Debug.Print swSelMgr.SuspendSelectionList
                swSelMgr.AddSelectionListObject swComp, Nothing
                swAssy.ReplaceComponents2 GetReplacementPath(swComp), swComp.ReferencedConfiguration, False, swReplaceComponentsConfiguration_e.swReplaceComponentsConfiguration_MatchName, True
                swSelMgr.ResumeSelectionList
            End If
        Next
    Else
        MsgBox ("Please open assembly document")
    End If
End Sub

Function GetReplacementPath(comp As SldWorks.Component2)
    Dim replFilePath As String
    Dim compPath As String
    compPath = comp.GetPathName()
    Dim dir As String
    dir = REPLACEMENT_DIR
    If Right(dir, 1) <> "\" Then
        dir = dir & "\"
    End If
    Dim fileName As String
    fileName = Right(compPath, Len(compPath) - InStrRev(compPath, "\"))
    If SUFFIX <> "" Then
        Dim ext As String
        ext = Right(fileName, Len(".SLDXXX"))
        fileName = Left(fileName, Len(fileName) - Len(ext)) & SUFFIX & ext
    End If
    replFilePath = dir & fileName
    GetReplacementPath = replFilePath
End Function

文章翻译自https://www.codestack.net/

仅供学习使用。

QR Code
微信扫一扫,欢迎咨询~

联系我们
武汉格发信息技术有限公司
湖北省武汉市经开区科技园西路6号103孵化器
电话:155-2731-8020 座机:027-59821821
邮件:tanzw@gofarlic.com
Copyright © 2023 Gofarsoft Co.,Ltd. 保留所有权利
遇到许可问题?该如何解决!?
评估许可证实际采购量? 
不清楚软件许可证使用数据? 
收到软件厂商律师函!?  
想要少购买点许可证,节省费用? 
收到软件厂商侵权通告!?  
有正版license,但许可证不够用,需要新购? 
联系方式 155-2731-8020
预留信息,一起解决您的问题
* 姓名:
* 手机:

* 公司名称:

姓名不为空

手机不正确

公司不为空