This website uses cookies to ensure you get the best experience on our website. By using our website you agree on the following Cookie Policy, Privacy Policy, and Terms Of Use
Dim swApp As SldWorks.SldWorks
Const EXPORT_NAME_TEMPLATE AsString = "[title]_[sketch].dxf"Sub main()
Set swApp = Application.SldWorks
try:
OnErrorGoTocatchDim swModel As SldWorks.ModelDoc2
Set swModel = swApp.ActiveDoc
Dim swSelMgr As SldWorks.SelectionMgr
Set swSelMgr = swModel.SelectionManager
Dim swSketchFeat As SldWorks.Feature
Set swSketchFeat = swSelMgr.GetSelectedObject6(1, -1)
If swSketchFeat.GetTypeName2() = "ProfileFeature"Then
swSketchFeat.Select2 False, -1
swModel.EditCopy
Dim drawTemplate AsString
drawTemplate = swApp.GetUserPreferenceStringValue(swUserPreferenceStringValue_e.swDefaultTemplateDrawing)
If drawTemplate = ""Then
Err.Raise vbError, "", "Failed to find the default template"EndIfDim swDraw As SldWorks.ModelDoc2
Set swDraw = swApp.NewDocument(drawTemplate, swDwgPaperSizes_e.swDwgPapersUserDefined, 0.1, 0.1)
swDraw.Paste
Dim errs AsLongDim warns AsLongDim exportFilePath AsString
exportFilePath = GetExportFilePath(swModel, swSketchFeat)
IfFalse = swDraw.Extension.SaveAs(exportFilePath, swSaveAsVersion_e.swSaveAsCurrentVersion, swSaveAsOptions_e.swSaveAsOptions_Silent, Nothing, errs, warns) Then
Err.Raise vbError, "", "Failed to export to DXF, DWG"EndIf
swApp.CloseDoc swDraw.GetTitle
Else
Err.Raise vbError, "", "Please select 2D sketch to export"EndIfGoTofinallycatch:
swApp.SendMsgToUser2 Err.Description, swMessageBoxIcon_e.swMbStop, swMessageBoxBtn_e.swMbOk
finally:
EndSubFunction GetExportFilePath(model As SldWorks.ModelDoc2, sketch As SldWorks.Feature) AsStringConst PLACEHOLDER_TITLE AsString = "[title]"Const PLACEHOLDER_SKETCH AsString = "[sketch]"Dim path AsStringDim dir AsStringDim title AsString
path = model.GetPathName
If path = ""Then
Err.Raise vbError, "", "Original model is never saved"EndIf
title = Mid(path, InStrRev(path, "\") + 1, InStrRev(path, ".") - InStrRev(path, "\") - 1)
dir = Left(path, InStrRev(path, "\"))
Dim newTitle AsStringDim newPath AsString
newTitle = Replace(EXPORT_NAME_TEMPLATE, PLACEHOLDER_TITLE, title)
newTitle = Replace(newTitle, PLACEHOLDER_SKETCH, sketch.Name)
newPath = dir & newTitle
GetExportFilePath = newPath
EndFunction
Notifications
Join session by SOLIDWORKS and PDM API expret Artem Taturevych at 3DEXPERIENCE World 2025 on Feb 26 at 08:30 AM CST to explore 10 essential macros for automating drawings, assemblies, custom properties, and more