CATVBA, CATIA incorrect selection - vba

I'm trying to alter a user selected parameter of a selected CATPart in an assembly via CADSelection. Ultimatelly this will go into a GUI in VBA and the user will, select the CATPart, open the macro and via the GUI change whatever parameters he requires.
I've recorded the macro and tweaked around with this for a while now, but i can't seem to finish this.
My tree is:
Product;
-Part;
-Part_Teste_2;
-Part_Teste_3;
-Part_Teste_4;
-Part_Teste_5;
All of the above "Part_Teste" have 3 parameters one of them is called "Comprimento"
How do I change make sure that the macro alters the selected CATPArt's parameter instead of ("Part_Teste_3.CATPart")?
The macro that I have so far is:
Language="VBSCRIPT"
Sub CATMain()
Set oProductDoc = CATIA.ActiveDocument
Set oProd = oProductDoc.Product
Set oDocs = CATIA.Documents
Set oSelection = CATIA.ActiveDocument.Selection
If oSelection.Count < 1 then
MsgBox "Pick some components using cad selection.","No components were selected"
Else
Set oPartDoc = oDocs.Item("Part_Teste_3.CATPart")
Set oPart = oPartDoc.Part
Set oParam = oPart.Parameters
Set oLength = oParam.Item("Comprimento")
oLength.Value = 50.000000
End If
oSelection.Clear
oProd.Update
End Sub

When you select in an assembly, the LeafProduct property of the SelectedEntity object returned by Selection.Item() will contain the instance product owning the selected object.
So, if you are selecting something which belongs to a part while working in an assembly, get the instance product of the part...
Dim oInstProd as Product
Set oInstProd = oSel.Item(1).LeafProduct
Then from there get the part object:
Set oPart = oInstProd.ReferenceProduct.Parent.Part

Related

How do I deactivate and reactivate several geometrical sets and objects automatically?

I wrote a macro that hides everything in several geometrical sets and the objects and geometrical sets in these first sets except one specific branch. I use this for saving a defined object of a huge and complicated specification tree as a STP file. (See attached below.)
(Small complication in this “Hide_and_Save” macro: adding bodies to my hide-selection works well but for my show-selection it didn’t work the same way. Why would this happen?)
I also wrote a macro that does iterative adjustments. For the iterations I use a Do While Loop and some parameters and measurements. To update these values, I have to update the part/object in every cycle. But there are some construction elements that issue errors until the loop is successfully completed. Therefore I deactivate all the geometrical sets that I don’t need for the iterations (inclusively all children) and later I reactivate them manually.
My goal is to improve automation, so I tried to use my “Hide_and_Save” macro for deactivation and reactivation. This didn’t work. When I record the process, each object is listed in a separate line and deactivated. Since there are more than 350 elements, I would like to avoid this.
How do I deactivate all subelements in a geometrical set (preferably with children) without addressing each element individually?
Attribute VB_Name = "Hide_and_Save"
'_______________________________________________________________________________________
'Title: Hide_and_Save
'Language: catvba
'_______________________________________________________________________________________
Sub CATMain()
'---------------------------------------------------------------------------------------
'Select active Part/Document
Dim myDocument As Document
Set myDocument = CATIA.ActiveDocument
Dim myPart As part
Set myPart = CATIA.ActiveDocument.part
'--------------------------------------------------------------
' Enter file path
Dim filepath As String
filepath = InputBox("Please select memory location", "Input filepath", "...")
If filepath = "" Then 'cancle, abort or empty input
MsgBox "No valid input / cancle !"
Exit Sub
End If
'--------------------------------------------------------------
' Hide/show Objects of Part/Products and save as STEP
' Update Model
CATIA.ActiveDocument.part.Update
' Deklaration of Selections and Properties
Dim selectionShow, selectionHide As Selection
Set selectionShow = myDocument.Selection
Set selectionHide = myDocument.Selection
Dim visPropertySetShow, visPropertySetHide As VisPropertySet
Set visPropertySetShow = selectionShow.VisProperties
Set visPropertySetHide = selectionHide.VisProperties
' Definition of the collection of geometric sets - HybridBodies
Dim hybridBodiesInPart, hybridBodiesInProcess As HybridBodies
Dim hybridBodiesInRS, hybridBodiesInHuelle As HybridBodies
' Definition of individual geometric sets - HybridBody
Dim hybridBodyInPart, hybridBodyProcess, hybridBodyInProcess As HybridBody
Dim hybridBodyRS, hybridBodyInRS As HybridBody
Dim hybridBodyHuelle, hybridBodyInHuelle As HybridBody
' Definition of the collection of 3D-objects - HybridShapes
Dim hybridShapesInHuelle As HybridShapes
' Definition of individual 3D-objects - HybridShape
Dim hybridShapeInHuelle, hybridShapeForm As HybridShape
' Hide objects
Set hybridBodiesInPart = myPart.HybridBodies
For Each hybridBodyInPart In hybridBodiesInPart
selectionHide.Add hybridBodyInPart
Next
Set hybridBodyProcess = hybridBodiesInPart.Item("Process")
Set hybridBodiesInProcess = hybridBodyProcess.HybridBodies
For Each hybridBodyInProcess In hybridBodiesInProcess
selectionHide.Add hybridBodyInProcess
Next
Set hybridBodyHuelle = hybridBodiesInProcess.Item("Huelle")
Set hybridBodiesInHuelle = hybridBodyHuelle.HybridBodies
For Each hybridBodyInHuelle In hybridBodiesInHuelle
selectionHide.Add hybridBodyInHuelle
Next
Set hybridShapesInHuelle = hybridBodyHuelle.HybridShapes
For Each hybridShapeInHuelle In hybridShapesInHuelle
selectionHide.Add hybridShapeInHuelle
Next
Set hybridShapeForm = hybridShapesInHuelle.Item("Form")
visPropertySetHide.SetShow 1 'hide
selectionHide.Clear
' Show objects
selectionShow.Add hybridBodyProcess
selectionShow.Add hybridBodyHuelle
selectionShow.Add hybridShapeForm
visPropertySetShow.SetShow 0 'show
selectionShow.Clear
' Data export as STP
stepAnswer = MsgBox("Should the displayed elements be saved as STEP?", 3 + 0, "Export: Form")
If stepAnswer = 6 Then
myDocument.ExportData filepath & "Form" & ".stp", "stp"
ElseIf stepAnswer = 3 Or stepAnswer = 2 Then 'cancle or abort
MsgBox "cancle !"
Exit Sub
End If
'---------------------------------------------------------------------------------------
MsgBox "Finished !" & vbCrLf & s
End Sub
(Usually I work with Generative Shape Design and use VBA for Macros.)
Each feature has an "Activity" parameter aggregated to it.
Dim oShape as HybridShape
For Each oShape In oGS.HybridShapes
Dim oActivity as Parameter
Set oActivity = oPart.Parameters.SubList(oShape,False).Item("Activity")
Call oActivity.ValuateFromString("False")
Next
Let me add that screwing with Activity of features is not a best practice. I NEVER do this myself. If you have access KBE (Specifically Knowledge Advisor Workbench) you can probably do what you want with Rules/Actions/Reactions, less coding and have a more robust model in the end.

How to select a value from a DropDownList in a Word Macro using VBA?

I am creating a macro using both vbscript and vba, this macro is being called by the script code and works well but when I try to select a value outside the macro itself, I keep getting an error about the way im trying to set the value.
I have named the dropdownlist as "Result" and when I try to set the value it does not work, I also tried with the default name "DropDownList" , but none of those options seems to work, maybe i am missing object references.
I already declared the objects that I need
Set objWord = CreateObject("Word.Application")
Set activeDoc= objWord.ActiveDocument
activeDoc.FormFields("Result").DropDown.Value = 2
The error i am getting right now is that "The Requested memeber of the coleection does not exist."
The only solution I can come up with is to set the value when I'm creating the dropdown in the macro:
ActiveDocument.Tables(1).Cell(Row: = 4, Column: = 4).Select
Set objCC =
Selection.Range.ContentControls.Add(wdContentControlDropDownList)
With objCC
.Title = "Result"
.Tag = "Result"
.DropdownListEntries.Add("Passed", "Passed").Select
End with
I got everything messed up, but in the end I realized what was my mistake. I wasn't using the tag so the Item was loose, I had to use the index of the correct content control
Set objCc = activeDoc.ContentControls.Item(5)
Set objLe1 = objCc.DropdownListEntries.Item(1)
objLe1.Select
Thanks very much for your part of code, I have so much trouble to find how to do this !
I add just :
With ThisDocument.tables(blabla).Cell(x,y)
Set objCc = .Range.ContentControls.Item(1)
Set objLe1 = objCc.DropdownListEntries.Item(2)
objLe1.Select
End With
And it works perfectly within my project ! Ty again, see you !

FTA Catia R24 Associative Front view (VBA)

does anyone know how to create Associative Front View in FTA using VBA. I have short macro to create Front View based on the geometry from 3D but this view is isolated and I must manually change it to Associative.
What I would like to have is Associative View created by macro. It is first step to perform macro for power copy.
Bellow my code.
Sub CATMain()
Dim partDocument1 As PartDocument
Set partDocument1 = CATIA.ActiveDocument
Dim part1 As PART
Set part1 = partDocument1.PART
'--------------------------------------------------
'Create Annotation Set
Dim annotationSet1 As AnnotationSet
Set annotationSet1 = part1.AnnotationSets.Add("ISO")
'Debug.Print annotationSet1.Name
Dim theViewFactory As TPSViewFactory
Set theViewFactory = annotationSet1.TPSViewFactory
'--------------------------------------------------
'Create reference plane from selection
Dim ViewPlane As Reference
Set Selection = partDocument1.Selection
Selection.Clear
Selection.Search ("name='Plane.6',all") 'Search plane by name
Set ViewPlane = Selection.Item(1).Value 'Set plane from selection
Selection.Clear
'--------------------------------------------------
'Create Front View
Dim theView As TPSView
Set theView = theViewFactory.CreateView(ViewPlane, 0)
theView.Name = "FrontView"
'--------------------------------------------------
'Create dimension
part1.Update
End Sub
As far I my knowlodge on Catia API go, it is not possible to associate a view using the API.
Also, using Win32 to perform clicks on buttons/comboboxes from handles will not work because to associate the view to a plane/surface you will need to perform a click on the desired location using the Catia User Interface.
the TPSView object on the API is probably one of the worse ones ever exposed, it doesn't have any property. Also, the TPSViewFactory and TPSViews don't have any usefull method to manager views.
So, the short answer is no, you can't do that.

Return different values from a vba user form depending on the button pressed

I have been creating an acronym finding macro that will sit on a custom toolbar in word. When run it searches the document for acronyms and places them in a table. I want to include some user forms so that as the macro finds an acronym the user can select the predefined definition (got from an excel document) or enter their own new one (I know multiple acronyms meanings is frowned upon but it happens).
Anyway I am stuck. I have created a user form with three buttons. A text input and a label. Now I have managed to set the label text with the acronym that was found however I can't seem to get the buttons to change a variable, userChoice, and if applicable save the newly entered definition.
below is the test macro i have been trying this out on
Sub userFormTest()
Dim objExcel As Object
Dim objWbk As Object
Dim rngSearch As Object
Dim rngFound As Object
Dim targetCellValue As String
Dim userChoice As Integer
Set objDoc = ActiveDocument
Set objExcel = CreateObject("Excel.Application")
Set objWbk = objExcel.Workbooks.Open("C:\Users\Dave\Documents\Test_Definitions.xlsx")
objExcel.Visible = True
objWbk.Activate
With objWbk.Sheets("Sheet1")
Set rngSearch = .Range(.Range("A1"), .Range("A" & .Rows.Count).End(-4162))
Set rngFound = rngSearch.Find(What:="AA", After:=.Range("A1"), LookAt:=1)
If rngFound Is Nothing Then
UserForm1.Label1.Caption = "Acronym: AA" & vbCr & _
"Definition: Not found, please enter a definition below" & vbCr & _
" or choose to ignore this acronym"
UserForm1.Show
'an if statement here so that if the add button was pressed it adds to doc etc
Else
targetCellValue = .Cells(rngFound.Row, 2).Value
UserForm2.Label1.Caption = "Acronym: AA" & vbCr & _
"Definition: " & targetCellValue
UserForm2.Show
'an if statement here so that if the add button was pressed it adds to doc etc
End If
End With
objWbk.Close Saved = True
Set rngFound = Nothing
Set rngSearch = Nothing
Set objWbk = Nothing
objExcel.Visible = True
Set objExcel = Nothing
Set objDoc = Nothing
End Sub
I do realise that this could be done in the button_click() subs however I already have all the documents open etc in the other macro. Or is it possible to link to those already open documents? To be honest either way I would prefer to return to the main macro and just use the form to the user input.
I do realise that this could be done in the button_click() subs. However I already have all the documents open etc in the other macro. Or is it possible to link to those already open documents?
You can definitely link between button_click() subs and your main macro to modify the value of userChoice.
Answer:
What you need is some userform element (like a textbox) that can hold your value so you can refer back to it in your main macro. It looks like you already have this element (based upon your caption "Not found, please enter a definition below"). Let's say that element is a TextBox called Definition. Then let's say you want to return to the main macro after people push an "Add" button, as it appears you do (based upon your comment "so that if the add button was pressed it adds to doc").
In each of both Userform1 and Userform2, you would want something like this:
Private Sub AddButton_Click()
Userform1/Userform2.Hide
End Sub
That would return you to your main macro, where you could follow up with:
If Userform1/Userform2.Definition.Value = Whatever Then
'if the add button was pressed it adds to doc etc
End If
right where your existing comments are. Note that you could set userChoice = Userform1.Definition.Value here, but you don't need to because Userform1.Definition.Value already contains the information you need to track.
Additional material:
Rather than using the default instance of your Userform1 and Userform2 by using .Show on them immediately without assigning new instances of them to variables, may I suggest creating Userform variables to contain New instances of them like this:
Dim UnknownDefinition As Userform1
Set UnknownDefinition = New Userform1
UnknownDefinition.Show
Or if you want to get really optimal, you could follow more of the approach recommended here on how to make a properly instanced, abstracted userform:
Rubberduck VBA: How to create a properly instanced, abstracted userform
And now with bonus quotes from the post's author, #Mathieu Guindon:
make Definition a proper property, with the Property Let mutator changing the label value on top of changing its private backing field's value; avoid accessing form controls outside the form, treat them as private even if VBA makes them public.
Calling code wants data, not controls. You can extract properties/data, but not controls, into a dedicated model class.

How can I programmatically modify an embedded bar/column chart with VBA?

I'm creating a ProcessBook display that populates an embedded Microsoft Office 11.0 Spreadsheet object (Office 2003) with a set of entries. I'm then calculating aggregate data about them; this aggregate data should not be visible in spreadsheet form onscreen, but does need to be used to generate a bar chart. The data is currently being used to populate a separate Microsoft Office 11.0 Spreadsheet object. It's organized such that the title of each bar chart is in column A and the corresponding value is in column B.
Since this is ProcessBook, I've had some difficulty even gaining access to embedded objects, but I've managed to embed and gain access to a ChartSpace object, as well as a child ChChart object. Unfortunately, I can't figure out how to either manually set the values of the bars or how to use the .SetData or .SetSpreadsheetData methods to point it to an object that I've populated.
Accessing the ChartSpace object is pretty straightforward: ThisDisplay.ChartSpace1
I can then add a Chart and access it fairly easily:
Dim objChart as ChChart
Set objChart = ThisDisplay.ChartSpace1.Charts.Add(0)
I can access my spreadsheet values pretty easily as well:
strBarName = ThisDisplay.sstChartData.Range("A2").Value
intBarVal = ThisDisplay.sstChartData.Range("B2").Value
How do I actually set the data source or manually set the values of the bars in the ChChart object? Alternatively, how do I use a different object to accomplish the same goal?
Apparently persistence is the key here. I managed to determine how to both add values manually and how to refer to the existing spreadsheet object. Both examples take heavily from the online ChChart documentation; I guess I was just tired when I attempted it in the first place and must have mistyped something somewhere.
Public Sub AddValuesToChartManually()
Dim objChart As ChChart
With ThisDisplay.ChartSpace1
Do While .Charts.Count > 0
ThisDisplay.ChartSpace1.Charts.Delete (0)
Loop
Set objChart = .Charts.Add
objChart.HasTitle = True
objChart.Title.Caption = "Chart Title"
objChart.Axes.Item(0).HasTitle = True
objChart.Axes.Item(1).HasTitle = True
objChart.Axes.Item(0).Title.Caption = "Axis 0"
objChart.Axes.Item(1).Title.Caption = "Axis 1"
objChart.HasLegend = False
Dim astrHeaders(0 To 4) As String
Dim aintValues1(0 To 4) As String
Dim aintValues2(0 To 4) As String
Dim astrSeries1(0) As String
Dim astrSeries2(0) As String
astrHeaders(0) = "AL1"
astrHeaders(1) = "AL2"
astrHeaders(2) = "AL3"
astrHeaders(3) = "AL4"
astrHeaders(4) = "AL5"
astrSeries(0) = "Series Name"
aintValues(0) = 1
aintValues(1) = 3
aintValues(2) = 17
aintValues(3) = 1
aintValues(4) = 7
objChart.Type = .Constants.chChartTypeColumnClustered
Call objChart.SetData(chDimSeriesName, .Constants.chDataLiteral, astrSeries)
Call objChart.SetData(chDimCategories, .Constants.chDataLiteral, astrHeaders)
Call objChart.SeriesCollection(0).SetData(.Constants.chDimValues, .Constants.chDataLiteral, aintValues)
End With
End Sub
Public Sub AddValuesFromSpreadsheet()
Dim objChart1 As ChChart
With ThisDisplay.ChartSpace1
Do While .Charts.Count > 0
ThisDisplay.ChartSpace1.Charts.Delete (0)
Loop
Set .DataSource = ThisDisplay.sstChartData
Set objChart1 = .Charts.Add
' Set the chart type.
objChart1.Type = .Constants.chChartTypeColumnClustered
' Display titles
objChart1.HasTitle = True
objChart1.Title.Caption = "Chart Title"
' Bind the series name to cell B1 in the first sheet of the spreadsheet
objChart1.SetData chDimSeriesNames, .Constants.chDataBound, "B1"
' Bind the category axis to cell A2:A28 in the first sheet of the spreadsheet.
objChart1.SetData chDimCategories, .Constants.chDataBound, "A2:A6"
' Bind the values of the data series to cells B2:B28 in the first sheet of the spreadsheet.
objChart1.SeriesCollection(0).SetData chDimValues, .Constants.chDataBound, "B2:B6"
End With
End Sub