Создание макроса Solidworks для сохранения детали в 3MF, STEP, STL
Для часто выполняемых задач, удобно использовать макросы.
В Solidworks используются макросы на VBA (Visual Basic for Applications), файлы с расширением .swp и .swb.
Инструменты для работы с макросами (запись, воспроизведение, создание и редактирование) можно найти в меню Tools или через поиск по запросу Macro.
Код макроса
Dim swApp As Object
Dim Part As Object
Dim boolstatus As Boolean
Dim longstatus As Long, longwarnings As Long
Dim folderFullPath As String
Sub main()
Set swApp = Application.SldWorks
Set Part = swApp.ActiveDoc
' check is .SLDPRT is opened
If Part Is Nothing Then
MsgBox "[ERROR] No active files found!"
Exit Sub
End If
' check is active document is .SLDPRT file
If Part.GetType <> swDocPART Then
MsgBox "[ERROR] Open .SLDPRT first!"
Exit Sub
End If
FilePath = Part.GetPathName ' Get the full path of the part/assembly file
FileTitle = Part.GetTitle ' Get the full part name
FileName = Strings.Left(FileTitle, Len(FileTitle) - 7)
PathSize = Strings.Len(FilePath) ' Get the length of the full path
TitleSize = Strings.Len(FileTitle) ' Get the length of the part name
FolderSize = Strings.Len(FilePath) - Strings.Len(FileTitle) ' Get the length of the folder
RootFolderName = Strings.Left(FilePath, FolderSize) ' Truncate to folder name
MfFolderPath = RootFolderName & "3mf\"
StlFolderPath = RootFolderName & "stl\"
StepFolderPath = RootFolderName & "step\"
'checking existing of 3mf, step, stl folders
If Dir(MfFolderPath) = "" Then
MsgBox "[ERROR] Folders '3mf', 'step' and 'stl' not found!"
MfFolderPath = RootFolderName
StlFolderPath = RootFolderName
StepFolderPath = RootFolderName
End If
MfFilePath = MfFolderPath & FileName & ".3mf"
StlFilePath = StlFolderPath & FileName & ".stl"
StepFilePath = StepFolderPath & FileName & ".step"
longstatus = Part.SaveAs3(MfFilePath, 0, 2)
longstatus = Part.SaveAs3(StlFilePath, 0, 2)
longstatus = Part.SaveAs3(StepFilePath, 0, 2)
MsgBox ("3MF, STEP and STL saved!")
'close the document
swApp.CloseDoc FileTitle
End SubОтдельные моменты работы макроса:
If Part Is Nothing Then MsgBox «[ERROR] No active files found!» Exit Sub End If
If Part.GetType <> swDocPART Then MsgBox «[ERROR] Open .SLDPRT first!» Exit Sub End If
FileName = Strings.Left (FileTitle, Len (FileTitle) — 7)
- Проверка на наличие папки 3mf (я храню файлы 3mf, step и stl в отдельных одноимённых папках). Если отдельная папка не найдена, то сохраняем в рядом с файлом детали .SLDPRT:
If Dir (MfFolderPath) = «» Then MsgBox «[ERROR] Folders '3mf', 'step', 'stl' not found!» MfFolderPath = RootFolderName StlFolderPath = RootFolderName StepFolderPath = RootFolderName End If
longstatus = Part.SaveAs3(MfFilePath, 0, 2) longstatus = Part.SaveAs3(StlFilePath, 0, 2) longstatus = Part.SaveAs3(StepFilePath, 0, 2)
swApp.CloseDoc FileTitle
Полный код макроса доступен по ссылке https://pastebin.com/UyHKDQm7
I. Создание макроса
1) Открываем Solidworks и переходим → Tools → Macro → New…
2) В открывшемся окне выбираем место хранения макроса и название, открывается пустой шаблон макроса
3) В окно редактирования вставляем код из https://pastebin.com/UyHKDQm7 и сохраняем (Ctrl+S или иконка «Дискета»)
II. Добавление кнопки макроса на панель инструментов
1) Создаем пустой документ детали .SLDPRT
2) В открывшемся окне детали переходим → Tools → Customize…
3) Далее переходим во вкладку → Shortcut Bars → Macro
4) Из поля Buttons перетягиваем крайнюю правую икону в удобное место на панели
5) Открывается меню редактирования кнопки макроса, заполняем поля
а) Macro: выбираем путь к макросу (введенный в пункте I.2 выше)
б) Icon: выбираем иконку (опционально)
в) Tooltip: вводим подпись кнопки
III. Проверяем работу макроса
1) Открываем или создаем деталь
2) Нажимаем кнопку макроса. Всплывающее окно сообщает об успешном сохранении файлов
3) Проверяем наличие файлов в папке
Видео вышеописанных действий: https://youtu.be/VSzb9d2xMxE