在后台执行 SolidWorks 并使用 VBA 宏退出

Execute SolidWorks in background and exit with VBA macro

我正在尝试使用 SolidWorks 和一个 VBA 宏来做一个复杂的几何图形,我用批处理脚本启动它。

首先,我做了一个简单的宏来检查是否可以在后台 运行 solidworks,创建一个新零件,做一个简单的立方体,然后保存并关闭它。

发生了两件我不想做的事情:solidworks GUI 实际上显示在我的屏幕上,并且 solidworks 在保存文档后不会自动退出。它只是关闭当前部分而不是软件。文档完美保存,几何图形正确。这是一个问题,因为我的主批处理宏无法继续 运行ning,除非我手动关闭软件。

代码如下:

Dim swApp As Object

Dim Part As Object
Dim boolstatus As Boolean
Dim longstatus As Long, longwarnings As Long

Sub main()

Set swApp = _
Application.SldWorks

Set Part = swApp.NewDocument("C:\ProgramData\SolidWorks\SOLIDWORKS 2015\templates\Pieza.prtdot", 0, 0, 0)

' "Pieza" means part
swApp.ActivateDoc2 "Pieza1", False, longstatus

Set Part = swApp.ActiveDoc

Dim myModelView As Object

' Use SolidWorks in background mode
swApp.Visible = False

Set myModelView = Part.ActiveView

myModelView.FrameState = swWindowState_e.swWindowMaximized

' Select lateral view and insert a sketch. Then extrude it
boolstatus = Part.Extension.SelectByID2("Vista lateral", "PLANE", 0, 0, 0, False, 0, Nothing, 0)
Part.SketchManager.InsertSketch True
Part.ClearSelection2 True
boolstatus = Part.Extension.SetUserPreferenceToggle(swUserPreferenceToggle_e.swSketchAddConstToRectEntity, swUserPreferenceOption_e.swDetailingNoOptionSpecified, False)
boolstatus = Part.Extension.SetUserPreferenceToggle(swUserPreferenceToggle_e.swSketchAddConstLineDiagonalType, swUserPreferenceOption_e.swDetailingNoOptionSpecified, True)

Dim vSkLines As Variant

vSkLines = Part.SketchManager.CreateCornerRectangle(0, 0, 0, -0.144655684475683, 8.79061467198382E-02, 0)
Part.ClearSelection2 True
Part.SketchManager.InsertSketch True
Part.ShowNamedView2 "*Trimétrica", 8
Part.ClearSelection2 True
boolstatus = Part.Extension.SelectByID2("Croquis1", "SKETCH", 0, 0, 0, False, 4, Nothing, 0)

Dim myFeature As Object

Set myFeature = Part.FeatureManager.FeatureExtrusion2(True, False, False, 0, 0, 0.2, 0.01, False, False, False, False, 1.74532925199433E-02, 1.74532925199433E-02, False, False, False, False, True, True, True, 0, 0, False)

Part.SelectionManager.EnableContourSelection = False
longstatus = Part.SaveAs3("C:\tmp_SW\part.SLDPRT", 0, 2)

' I tried to use a variable as a string, however using "swApp.QuitDoc Part.GetTitle" gives the same result
Dim myTitle As String

myTitle = Part.GetTitle

swApp.QuitDoc myTitle

End Sub

我希望西班牙语单词不会成为理解文本的问题。

提前致谢。

好吧,经过几天的研究,我发现了这个漂亮的例子:

SolidWorks Example

我的答案的关键是:

Sub Macro3()

     Dim swApp As Object

     Dim Part As Object

     Set swApp = CreateObject("SldWorks.Application")

     ' Whether this value was true or false I got the same. GUI is shown on screen... 
     swApp.Visible = True


     ' First put swApp and then set it to nothing, to close the document.
     swApp.ExitApp

     Set swApp = Nothing

End Sub

希望对大家有所帮助。最好的问候。