我想自动打开
.sldprt
文件,迭代其配置,并保存每个配置。此进程还应处理指定文件夹中的所有文件。目前,它通过 SolidWorks VBA 手动工作,但需要自动化。
问题:
我需要自动化打开多个 SolidWorks 零件文件的过程,将这些零件中的每个配置保存为单独的文件,然后继续处理文件夹中的下一个零件。经过一些研究和实验,我找到了一个解决方案,并想与可能面临同样挑战的其他人分享。
下面是完整的批处理脚本和 SolidWorks VBA 代码,可帮助实现此目的。批处理脚本打开 SolidWorks,为每个零件运行宏,然后在处理下一个文件之前关闭 SolidWorks。
答案:
要自动将零件的每个配置保存为单独的文件,请结合使用批处理脚本和 SolidWorks VBA。批处理脚本为每个零件打开 SolidWorks,运行保存每个配置的宏,然后在完成零件后关闭 SolidWorks。以下是您需要的批处理和 VBA 脚本:
批处理脚本:
@echo off
:: Define paths
set "SOLIDWORKS_PATH=where your solidworks .exe file is located."
set "MACRO_PATH=C:\NewConfig.swp where your macro is located"
set "PARTS_FOLDER=where your parts are located"
:: Loop through all SLDPRT files in the folder
for %%f in ("%PARTS_FOLDER%\*.sldprt") do (
echo Processing: %%f
"%SOLIDWORKS_PATH%" /r /m "%MACRO_PATH%" /n "%%f"
echo Waiting for SolidWorks to close...
:: Wait for SolidWorks to close before continuing to the next file
:WaitForSW
tasklist | find /i "SLDWORKS.exe" >nul
if not errorlevel 1 (
timeout /t 1 >nul
goto :WaitForSW
)
echo SolidWorks closed. Proceeding to the next file...
)
echo All parts processed!
pause
SolidWorks VBA 宏:
Sub main()
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim partPath As String
Dim savePath As String
' Initialize SolidWorks application
Set swApp = Application.SldWorks
' Get the currently open document (the file passed via batch script)
Set swModel = swApp.ActiveDoc
If swModel Is Nothing Then
MsgBox "No document is open. Ensure a part file is passed to the macro.", vbExclamation
swApp.ExitApp
Exit Sub
End If
' Validate that it's a part file
If swModel.GetType <> swDocPART Then
MsgBox "The open document is not a part file.", vbExclamation
swApp.ExitApp
Exit Sub
End If
' Process the active part
partPath = swModel.GetPathName
savePath = "S:\Departmental Folders\applications\Drawings\Munters\PreStudyEval_12-2024\170-012102" ' Adjust this as needed
ProcessConfigurations swModel, savePath
' Close the part and exit SolidWorks
swApp.CloseDoc swModel.GetTitle
swApp.ExitApp
End Sub
Sub ProcessConfigurations(swModel As SldWorks.ModelDoc2, savePath As String)
Dim swPart As SldWorks.PartDoc
Dim configNames As Variant
Dim i As Integer
Dim newFileName As String
Set swPart = swModel
configNames = swPart.GetConfigurationNames
For i = LBound(configNames) To UBound(configNames)
' Activate the configuration
swPart.ShowConfiguration2 configNames(i)
' Save the configuration as a new part
newFileName = savePath & configNames(i) & ".sldprt"
Debug.Print "Saving configuration: " & configNames(i) & " as " & newFileName
swModel.SaveAs3 newFileName, 0, 0
Next i
End Sub
说明:
批处理脚本:此脚本循环指定文件夹中的所有零件文件,在 SolidWorks 中打开每个文件,并为每个零件运行宏。每个零件完成处理后,SolidWorks 将关闭,然后再移至下一个零件。
VBA 脚本:此脚本在 SolidWorks 中执行,并将当前打开的零件的每个配置保存到新文件中。它处理每个配置并将它们保存到定义的保存路径。
注意: 确保更新批处理脚本和 VBA 宏中的路径以匹配您的本地设置。
此方法自动执行将每个配置保存在文件夹中的部分的过程,与手动操作相比,这可以节省大量时间。如果您有任何疑问或需要进一步帮助,请随时联系。