Delete Solidworks drawing Detail view - vba

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

Related

STEP to STL script stops after 478 itterations with runtime error 91?

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

Populate PDF Combo Box Via VBA

I have the below code to populate a combobox in a PDF document. As far as I can tell, the code is correct, according to the Acrobat Forms API Reference
However the code fails on the PopulateListOrComboBox call with this error:
Method 'PopulateListOrComboBox' of object 'IField' failed
Dim acroApp As Acrobat.acroApp
Set acroApp = New Acrobat.acroApp
Dim myForm As Acrobat.AcroAVDoc
Set myForm = New Acrobat.AcroAVDoc
Dim bOK As Boolean
bOK = myForm.Open("C:\Users\sholtzman\downloads\wordFormTest.pdf", "temp")
Dim theRealForm As AFORMAUTLib.AFormApp
Set theRealForm = New AFORMAUTLib.AFormApp
Dim pdField As AFORMAUTLib.Field
Set pdField = theRealForm.Fields.Add("triaCoverage", "combobox", 0, 10, 20, 100, 200)
Dim items(2) As String
items(0) = " "
items(1) = "Accept"
items(2) = "Reject"
pdField.PopulateListOrComboBox items
Furthermore, I tested this piece of code as well to try to fill it, but it also failed with the error:
Automation error Unspecified error
Dim myPDForm As Acrobat.AcroPDDoc
Set myPDForm = myForm.GetPDDoc
Dim jso As Object
Set jso = myPDForm.GetJSObject
jso.getField("triaCoverage").setItems(1) = " "
Lastly, when I save and close the document after adding the combobox, I can go in
and set list values manually. Any ideas how I can get this to work through code?
I did some more research and have found one answer just now by replacing the line:
jso.getField("triaCoverage").setItems(1) = " "
with
jso.getField("triaCoverage").setItems(items)
However, I prefer to use the PopulateListOrComboBox method if at all possible, so i will leave this unanswered for some time.

Autocad VBA - Create Square

I'm trying to make a simple square in AutoCAD using VBA but when I try to run my code I get an "Out of Range" Error? Any help would be great!
Sub box()
'Link the Exel File to the open CAD File'
'If no CAD file open it does create one'
'----------------------------------------------------------------'
Dim ACAD As AcadApplication 'Create ACAD variable of type AcadApplication
On Error Resume Next 'This tells VBA to ignore errors
Set ACAD = GetObject(, "AutoCAD.Application") 'Get a running instance of the class AutoCAD.Application
On Error GoTo 0 'This tells VBA to go back to NOT ignoring errors
If ACAD Is Nothing Then 'Check to see if the above worked
Set ACAD = New AcadApplication 'Set the ACAD variable to equal a new instance of AutoCAD
ACAD.Visible = True 'Once loaded, set AutoCAD® to be visible
End If
ACAD.ActiveDocument.Utility.Prompt "Hello from Excel!" 'Print a message to the AutoCAD® command line
Dim squareObj As Acad3DSolid
Dim center(0 To 2) As Double
center(0) = 10
center(1) = 10
center(2) = 0
Set squareObj = ACAD.ActiveDocument.ModelSpace.AddBox(center, 2, 2, 0)
End Sub
From Autodesk
https://knowledge.autodesk.com/search-result/caas/CloudHelp/cloudhelp/2016/ENU/AutoCAD-ActiveX/files/GUID-DE469E81-8531-415C-9D22-7041A42838DD-htm.html
RetVal = object.AddBox(Origin, Length, Width, Height)
The height of the box. Must be a positive number since it seems like autocad won't create a 3d solid with zero height.

CatiaV5 macro: how to insert background view?

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")

Execute SolidWorks in background and exit with VBA macro

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.