|
经典图书 Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Const LIBRARY_PATH = "D:\设计库\" ' 修改为实际库路径
Sub Main()
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
If Not IsAssembly(swModel) Then Exit Sub
Dim comp As Component2
For Each comp In GetComponents(swModel)
ProcessComponent comp
Next
End Sub
Function IsAssembly(doc As ModelDoc2) As Boolean
IsAssembly = (doc.GetType = swDocumentTypes_e.swDocASSEMBLY)
If Not IsAssembly Then MsgBox "请先打开装配体文件!"
End Function
Function GetComponents(doc As ModelDoc2) As Variant
Dim vComps As Variant
vComps = doc.GetComponents(True)
GetComponents = vComps
End Function
Sub ProcessComponent(comp As Component2)
If comp.IsVirtual Then Exit Sub
Dim srcPath As String
srcPath = comp.GetPathName
If IsFromLibrary(srcPath) Then
Dim destFolder As String
destFolder = GetAssemblyFolder(swModel)
' 复制零件文件
Dim prtDest As String
prtDest = CopyFileWithRename(srcPath, destFolder)
' 查找并复制工程图
CopyDrawing srcPath, destFolder
' 更新装配体引用(可选)
swModel.ReplaceReferencedDocument srcPath, prtDest, False
End If
End Sub
Function IsFromLibrary(path As String) As Boolean
IsFromLibrary = (InStr(1, path, LIBRARY_PATH, vbTextCompare) > 0)
End Function
Function GetAssemblyFolder(doc As ModelDoc2) As String
Dim fullPath As String
fullPath = doc.GetPathName
GetAssemblyFolder = Left(fullPath, InStrRev(fullPath, "\"))
End Function
Function CopyFileWithRename(src As String, destFolder As String) As String
Dim fso As Object: Set fso = CreateObject("Scripting.FileSystemObject")
Dim baseName As String: baseName = fso.GetBaseName(src)
Dim ext As String: ext = fso.GetExtensionName(src)
Dim counter As Long: counter = 1
Dim destPath As String
Do
destPath = destFolder & baseName & IIf(counter > 1, "_" & counter, "") & "." & ext
counter = counter + 1
Loop While fso.FileExists(destPath)
fso.CopyFile src, destPath
CopyFileWithRename = destPath
End Function
Sub CopyDrawing(prtPath As String, destFolder As String)
Dim fso As Object: Set fso = CreateObject("Scripting.FileSystemObject")
Dim drwPath As String: drwPath = fso.BuildPath(fso.GetParentFolderName(prtPath), fso.GetBaseName(prtPath)) & ".SLDDRW"
If fso.FileExists(drwPath) Then
CopyFileWithRename drwPath, destFolder
End If
End Sub
|
|