I am trying to do a complex geometry using SolidWorks and a VBA macro that I launch it with a batch script.
Firstly I did a simple macro to check if it is possible to run solidworks in background, creating a new part, doing a simple cube and then save it & close it.
Two things happens that I don't want to: the solidworks GUI actually is shown in my screen and the solidworks don't automatically exit after saving the document. It just closes the current part but not the software. The document is perfectly saved and the geometry is correct. It is a problem because my main batch macro cannot continue running unless I close the software manually.
Here is the code:
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
I hope the spanish words won't be a problem for understanding the text.
Thanks in advance.
Well, few days of research and I have found this beautiful example:
SolidWorks Example
And the key to my answer was:
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
I hope this will help you all. Best regards.
Related
I need to delete unnecessary detail views in specified Solidworks drawing, but I need to use late binding. First I try to delete Detail view from feature tree, but then it delete only Detail view leaving sketched circle. Then I delete Detail view in drawing, same result. Then Detail view circle, same result. Last I try delete sketched circle, but it doesn't select certain circle. When this code is compile in Solidworks API, all is working correctly, but when this is compile in Excel VBA, then it does this weird thing. I have suspicion that this is connected with late binding. Any suggestions?
Dim SwApp
On Error Resume Next
Set SwApp = GetObject(, "SldWorks.Application")
'If Solidworks is not started then start it
If Err.Number <> 0 Then
Set SwApp = CreateObject("SldWorks.Application")
End If
SwApp.Visible = True
Dim InitialDrawing2 As Object
Set InitialDrawing2 = SwApp.Opendoc(FormatSketchTemplateFolder & "FormatSketch+Tray.SLDDRW", 3)
Dim Status As Boolean
Status = InitialDrawing2.Extension.SelectByID2("Detail Circle2", "DETAILCIRCLE", 0, 0, 0, False, 0, Nothing, 0)
InitialDrawing2.EditDelete
Status = InitialDrawing2.Extension.SelectByID2("Arc1", "SKETCHSEGMENT", 0, 0, 0, False, 0, Nothing, 0)
InitialDrawing2.EditDelete
After several hours I found an error.
Before selecting circles needs to select certain drawing view
Dim SwApp
On Error Resume Next
Set SwApp = GetObject(, "SldWorks.Application")
'If Solidworks is not started then start it
If Err.Number <> 0 Then
Set SwApp = CreateObject("SldWorks.Application")
End If
SwApp.Visible = True
Dim InitialDrawing2 As Object
Set InitialDrawing2 = SwApp.Opendoc(FormatSketchTemplateFolder & "FormatSketch+Tray.SLDDRW", 3)
Dim Status As Boolean
InitialDrawing2.ActivateView ("Drawing View9")
Status = InitialDrawing2.Extension.SelectByID2("Detail Circle2", "DETAILCIRCLE", 0, 0, 0, False, 0, Nothing, 0)
InitialDrawing2.EditDelete
Status = InitialDrawing2.Extension.SelectByID2("Arc1", "SKETCHSEGMENT", 0, 0, 0, False, 0, Nothing, 0)
InitialDrawing2.EditDelete
I have encountered a very odd error. When I run my STEP to STL conversion VBA script, it runs flawlessly for 478 itterations and then stops with the following message:
Run-time error '91': Object variable or With block variable not set
the debugger shows the error on the line Set swModelDocExt = swModel.Extension, but it happens because the variable swPart is Nothing even though the line Set swPart = swApp.LoadFile4(stepFileName, "r", swImportStepData, errors) was run.
I have run this script many times for different data, and it throws the above error after exactly 478 itterations every time.
The script runs again for 478 itterations after closing and re-opening Solidworks!
My .STEP files are organized as follows:
C:\mydata\beams\0\beam.step
C:\mydata\beams\1\beam.step
C:\mydata\beams\2\beam.step
...
C:\mydata\beams\500\beam.step
etc.
In this file bin you find a beam.step file, as well as my solidworksDummyPart.SLDPRT file that I load initially to make sure solidworks functions propperly.
'-------------------------------------------------------------------------------
' Preconditions: Verify that the specified SOLIDWORKS part document to open exists.
'
' Postconditions:
' 1. Opens Dummy Solidworks File
' 2. Closes Dummy File
' 3. For i (0:15000)
' 3.1 Imports the STEP file
' 3.2 Runs import diagnostics on the STEP file and repairs
' the bad faces.
' 3.3 Examine the FeatureManager design tree and graphics area.
' 3.4 Exports STL file
'-------------------------------------------------------------------------------
Option Explicit
Dim swApp As SldWorks.SldWorks
Dim swPart As SldWorks.PartDoc
Dim swModel As SldWorks.ModelDoc2
Dim swModelDocExt As SldWorks.ModelDocExtension
Dim swImportStepData As SldWorks.ImportStepData
Dim status As Boolean
Dim errors As Long
Dim warnings As Long
Dim fileName As String
Dim stepFileName As String
Dim datasetPath As String
Dim datapointPath As String
Dim longstatus As Long
Dim i As Integer
Dim counter As Integer
Sub main()
Set swApp = Application.SldWorks
'Open the SOLIDWORKS part document to export to a STEP file
fileName = "C:\mydata\solidworksDummyPart.SLDPRT"
Set swPart = swApp.OpenDoc6(fileName, swDocumentTypes_e.swDocPART, swOpenDocOptions_e.swOpenDocOptions_Silent, "", errors, warnings)
Set swModel = swPart
Set swModelDocExt = swModel.Extension
'Close Dummy Part
Set swPart = Nothing
swApp.CloseDoc "solidworksDummyPart.SLDPRT"
datasetPath = "C:\mydata\beams\"
'Export the SOLIDWORKS part document to a STEP file
counter = 0
For i = 0 To 500
datapointPath = datasetPath & CStr(i)
stepFileName = datapointPath & "\body.STEP"
'Get import information
Set swImportStepData = swApp.GetImportFileData(stepFileName)
'If ImportStepData::MapConfigurationData is not set, then default to
'the environment setting swImportStepConfigData; otherwise, override
'swImportStepConfigData with ImportStepData::MapConfigurationData
swImportStepData.MapConfigurationData = True
'Import the STEP file
Set swPart = swApp.LoadFile4(stepFileName, "r", swImportStepData, errors)
Set swModel = swPart
Set swModelDocExt = swModel.Extension
'Run diagnostics on the STEP file and repair the bad faces
status = swModelDocExt.SelectByID2("Imported1", "BODYFEATURE", 0, 0, 0, False, 0, Nothing, 0)
swModel.ClearSelection2 True
errors = swPart.ImportDiagnosis(True, False, True, 0)
swModel.ClearSelection2 True
' Save As .STL file
longstatus = swPart.SaveAs3(datapointPath & "\body.STL", 0, 0)
'record last saved STL
Debug.Print "Counter: " & CStr(counter) & Chr(9) & "Datapoint: " & CStr(i)
'Reset & Close
Set swPart = Nothing
swApp.CloseDoc "body.SLDPRT"
counter = counter + 1
Next i
End Sub
I have tried using an IF statement to check if swPart is 'nothing' and tried to re-load the file in the hope that it only failed initially. File exists! I can guarantee that, and also, I can continue the code simply by running the for loop from where it stopped.
E.g. If I started it at 1 and it stopped at 477, then I can start the for loop at 477 and it will run flawlessly if I restart Solidworks before I rerun the code.
I am looking for a solution that doesn't require me to restart Solidworks.
I am running Solidworks 2018 SP4.0
I have successfully been able to convert a word doc to pdf - but I can't get the winword process to end.
Dim wordApplication As Object = New Microsoft.Office.Interop.Word.Application
Dim wordDocument As Object
wordApplication.displayalerts = Word.WdAlertLevel.wdAlertsNone
wordDocument = New Microsoft.Office.Interop.Word.Document
'wordDocument = Nothing
Dim outputFilename As String
Dim filename As String
filename = "c:\TestInvoice.doc"
Try
wordDocument = wordApplication.Documents.Open(filename, ReadOnly:=False)
outputFilename = System.IO.Path.ChangeExtension(filename, "pdf")
If Not wordDocument Is Nothing Then
wordDocument.ExportAsFixedFormat(outputFilename, Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF, False, Microsoft.Office.Interop.Word.WdExportOptimizeFor.wdExportOptimizeForOnScreen, Microsoft.Office.Interop.Word.WdExportRange.wdExportAllDocument, 0, 0, Microsoft.Office.Interop.Word.WdExportItem.wdExportDocumentContent, True, True, Microsoft.Office.Interop.Word.WdExportCreateBookmarks.wdExportCreateNoBookmarks, True, True, False)
End If
'Threading.Thread.Sleep(3000)
If File.Exists(System.IO.Path.ChangeExtension(filename, "pdf")) Then
MessageBox.Show(System.IO.Path.ChangeExtension(filename, "pdf"))
End If
'wordDocument = Nothing
'wordApplication.Documents(filename).Close(Word.WdSaveOptions.wdDoNotSaveChanges)
'wordDocument.dispose()
'wordApplication.quit(False)
wordDocument.close()
wordApplication.application.quit(False)
wordApplication = Nothing
I've tried pretty much everything and have been scratching my head for the past few days - can you point me in the right direction?
Have you tried a Using statement?
Try wrapping everything in this.
Using wordApplication As Object = New Microsoft.Office.Interop.Word.Application
End Using
I'm making a macro to automatically open a new drawing on the correct sheet format with filled in title block but I can't seem to figure out how to insert a pre-made .CATDrawing in the same way the following option in the page setup dialog box would:
see here: https://i.imgur.com/goClGIh.png
my current progress looks like this:
Sub CATMain()
Dim partDoc As PartDocument
Set partDoc = CATIA.ActiveDocument
Dim myParam As Parameter
Set myParam = partDoc.Part.parameters.Item("Description")
Dim documents1 As Documents
Set documents1 = CATIA.Documents
Dim MyDrawingDoc As DrawingDocument
Set MyDrawingDoc = documents1.Add("Drawing")
MyDrawingDoc.Standard = catISO
Dim MyDrawingSheets As DrawingSheets
Set MyDrawingSheets = MyDrawingDoc.Sheets
Dim MyDrawingSheet As DrawingSheet
Set MyDrawingSheet = MyDrawingSheets.Item("Sheet.1")
MyDrawingSheet.PaperSize = catPaperA3
MyDrawingSheet.[Scale] = 1#
MyDrawingSheet.Orientation = catPaperLandscape
**CATIA.StartCommand "Page Setup"**
Dim dView As DrawingViews
Set dView = MyDrawingSheet.Views
dView.Item("Background View").Activate
AddTextWithLinkedParameter dView, 20, 20, myParam
End Sub
Sub AddTextWithLinkedParameter(dViewToContainTheText As DrawingViews, xPos, yPos, Optional param As Parameter)
Dim dtext As DrawingText
Set dtext = dViewToContainTheText.ActiveView.Texts.Add("", xPos, yPos)
If Not param Is Nothing Then
dtext.InsertVariable 0, 0, param
End If
End Sub
This line here
CATIA.StartCommand "Page Setup"
should be replaced by a sequence of codes that does the same thing as clicking the options would as shown in the image above.
In my experience, I think you are better off writing a script to draw a title block rather than using a template. This way it's more flexible with regards to changing sheet size and orientation. You can also update the titleblock if sheet size and orientation changes. This is also how catia does titleblocks with the catscript. I would avoid StartCommand as it's not inline with the script execution.
That being said. If you want to use a "template", then the best way to do that is to setup your template catDrawing and then your script will open the template as read-only, do what you need, and then the user will save-as. Avoid StartCommand if you can.
Directly opening the .CATdrawing template has the same result.
One can do this by using the follwing code:
Dim documents1 As Documents
Set documents1 = CATIA.Documents
Dim mydrawingdoc As DrawingDocument
Set mydrawingdoc = documents1.Open("Path\Template.CATDrawing")
Looked all around and could not find it. Need a macro so that I can repeat it 695 times, on 695 different files I have. Documentation is kind of uneasy, or I am unlucky.
I could do it in Microsoft VBA as follows:
Sub VbaBlackies
Dim oSl As Slide
For Each oSl In ActivePresentation.Slides
With oSl
.FollowMasterBackground = msoFalse
.DisplayMasterShapes = msoFalse
With .background
.Fill.ForeColor.RGB = RGB(0, 0, 0)
.Fill.BackColor.RGB = RGB(0, 0, 0)
End With
End With
Next oSl
End Sub
I am looking for something similar in LibreOffice BASIC. I could get started in the code this way:
Sub Main
Dim oDoc As Object
Dim oDPages As Object
Dim oDPage As Object
oDoc= ThisComponent
oDPages = oDoc.getDrawPAges()
For i=0 To oDPages.count()-1
oDPage = oDPages.getByIndex(i)
oDPage.Background = RGB(0,0,0) 'This does not work.
'I have no idea on how to access the object's properties and alter them.
Next i
End Sub
Any ideas, please?
What you are looking for is in Listing 15.1 of Andrew Pitonyak's macro document, an essential reference for macro programming.
Sub ChangeBackground
Dim oDoc as Object
oDoc = ThisComponent
Dim oDrawPages as Object, oDrawPage as Object
oDrawPages = oDoc.getDrawPages()
oDrawPage = oDrawPages.getByIndex(0)
Dim oBackground as Object
oBackground = oDoc.createInstance("com.sun.star.drawing.Background")
oBackground.FillColor = RGB(250,0,0)
oDrawPage.Background = oBackground
End Sub
API documentation is at https://www.openoffice.org/api/docs/common/ref/com/sun/star/drawing/Background.html.
YES! Worked like a charm, thanks a lot for the answers!
This is the final code that worked out for me:
Sub Main
Dim oDoc As Object
Dim oDPages As Object
Dim oDPage As Object
oDoc = ThisComponent
oDPages = oDoc.getDrawPAges()
For i=0 To oDPages.count()-1
oDPage = oDPages.getByIndex(i)
Dim oBackground As Object
oBackground = oDoc.createInstance("com.sun.star.drawing.Background")
oBackground.FillColor = RGB(0,0,0)
oDPage.Background = oBackground
Next i
End Sub