Solidworks macro to rotate parts with respect to the assembly axis - vba

I hope everybody's fine.
I am working with a solidworks macro that rotates an assembly component with respect to the assembly axis as its point of rotation.
I have this code below:
Sub RotateX()
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim swSelMgr As SldWorks.SelectionMgr
Dim swMath As SldWorks.MathUtility
Dim swComp As SldWorks.Component2
Dim compTransform As SldWorks.MathTransform
Dim swVect As MathVector
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
Set swSelMgr = swModel.SelectionManager
Set swComp = swSelMgr.GetSelectedObjectsComponent2(1)
Set swMath = swApp.GetMathUtility
'==============================
On Error Resume Next
'==============================
Set compTransform = swComp.Transform2
Dim dirArr(2) As Double
dirArr(0) = 1
dirArr(1) = 0#
dirArr(2) = 0#
'Rotate about x axis {1,0,0}
Set swVect = swMath.CreateVector((dirArr))
Set swVect = swVect.MultiplyTransform(compTransform)
'rotate the x axis into the component's reference frame
Dim vData As Variant
dirArr(0) = 0#
dirArr(1) = 0#
dirArr(2) = 0#
'rotate about origin
vData = dirArr
Dim swPoint As SldWorks.MathPoint
Set swPoint = swMath.CreatePoint(vData)
Set swPoint = swPoint.MultiplyTransform(compTransform)
Dim swXform As SldWorks.MathTransform
Set swXform = swMath.CreateTransformRotateAxis(swPoint, swVect, 90# * RadPerDeg)
swComp.Transform2 = compTransform.Multiply(swXform)
swModel.EditRebuild3
End Sub
But this code rotates using the part axis as point of rotation.
I want to make a macro that rotates the part using assembly axis, but the part location will still doesnt move its position, just rotates.
I hope someone could help give me answer on how to make this part rotate on assembly axis.

by using:
Set swPoint = swPoint.MultiplyTransform(compTransform)
you're defining the point of rotation to be the center of the part.
Remove it and it will work.
Note: You might also have the same kind of problem with:
Set swVect = swVect.MultiplyTransform(compTransform)
where the rotation axis will depend of the orientation of the part.

Related

Creating new sketch in a planar face

In CATIA, a new sketch can be created on a origin plane (XY, YZ, XZ) or a planar face of a object. I have a pad and want to take its top face as the support plane for the next pocket operation. I've strived to do it by the latter but without success due to the failure of Add method in Sketches collection. What was I wrong about?
Here are a piece of my code, which produces the error:
Dim reference3 As Reference
Set reference3 = product1.CreateReferenceFromName("Assembly_Two_Parts/Chi_Tiet_1.1/!Selection_RSur:(Face:(Brp:(Pad.1;0:(Brp:(Sketch.1;1)));None:();Cf11:());Pad.1_ResultOUT;Z0;G6937)")
Set Sketch2 = MyBody1.Sketches.Add(reference3)
Set MyFactory2 = Sketch2.OpenEdition()
Set Circle1 = MyFactory2.CreateClosedCircle(0, 0, 5)
Sketch2.CloseEdition
your string reference is not possible in automation... or you gonna have difficult.
If it can help you :
Sub CATMain()
Dim s ' as selection
Dim myProduct As Product
Dim myPart As Part
Dim myRef 'as reference
'selection of face
Set s = CATIA.ActiveDocument.Selection
s.Clear
Dim Filters(0)
Filters(0) = "PlanarBiDimInfinite" 'after the comment from Shrotter
Status = s.SelectElement2(Filters, "Select a face", True)
If (Status = "Cancel") Then Exit Sub
Set myRef = s.Item2(1).Value
'get your part
Set myProduct = s.Item2(1).LeafProduct
Set myPart = CATIA.Documents.Item(myProduct.PartNumber & ".CATPart").Part
s.Clear
'set your circle in sketch
myPart.InWorkObject = myPart.MainBody
Dim myCircle As Sketch
Set myCircle = myPart.MainBody.Sketches.Add(myRef)
Dim myCircle_ As Circle2D
Set myCircle_ = myCircle.OpenEdition.CreateClosedCircle(0, 0, 50)
'update your part
myPart.Update
End Sub
my website : https://www.catiavb.net/

Create two(2) edge flanges in Solidworks with VBA

Dear SolidWorks users,
I am using SW2012 and via VBA I like to create two(2) edge flanges. I have the following code, this creates one edge flange after you select one edge of the sheet metal.
I like to know how can I add(put) 2 selections edge in an array? Like that (maybe), can be created two(2) edge flanges.
In the function of .InsertSheetMetalEdgeFlange2 it is mention that this function can accept array selection and array sketch.
Thank you.
Sub Bends_2()
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim swEdge As SldWorks.Edge
Dim swFeature As SldWorks.Feature
Dim swEntity As SldWorks.Entity
Dim swSketch As SldWorks.Sketch
Dim swSketchLine As SldWorks.SketchLine
Dim swStartPoint As SldWorks.SketchPoint
Dim swEndPoint As SldWorks.SketchPoint
Dim aFlangeEdges(0) As SldWorks.Edge
Dim aSketchFeats(0) As SldWorks.Sketch
Dim vFlangeEdges As Variant
Dim vSketchFeats As Variant
Dim bValue As Boolean
Dim dAngle As Double
Dim dLength As Double
Dim vSketchSegments As Variant
' Connect to SOLIDWORKS
Set swApp = Application.SldWorks
' Get active document
Set swModel = swApp.ActiveDoc
' Set the angle +length
dAngle = (90# / 180#) * 3.1415926535897
dLength = 25 / 1000
swModel.ShowNamedView2 "*Trimetric", -1
swModel.ViewZoomtofit2
' Get edge
Set swEdge = swModel.SelectionManager.GetSelectedObject6(1, -1)
' Insert a sketch for an Edge Flange
Set swFeature = swModel.InsertSketchForEdgeFlange(swEdge, dAngle, False)
' Select
bValue = swFeature.Select2(False, 0)
' Start sketch editing
swModel.EditSketch
' Get the active sketch
Set swSketch = swModel.GetActiveSketch2
' Add the edge to the sketch
Set swEntity = swEdge
' Select edge
bValue = swEntity.Select4(False, Nothing)
' Use the edge in the sketch
bValue = swModel.SketchManager.SketchUseEdge(False)
' Get the created sketch line
vSketchSegments = swSketch.GetSketchSegments
Set swSketchLine = vSketchSegments(0)
' Get start and end point
Set swStartPoint = swSketchLine.GetStartPoint2
Set swEndPoint = swSketchLine.GetEndPoint2
' Create additional lines to define sketch
swModel.SetAddToDB True
swModel.SetDisplayWhenAdded False
swModel.CreateLine2 swStartPoint.X, swStartPoint.Y, 0#, swStartPoint.X, swStartPoint.Y + dLength, 0#
swModel.CreateLine2 swStartPoint.X, swStartPoint.Y + dLength, 0#, swEndPoint.X, swStartPoint.Y + dLength, 0#
swModel.CreateLine2 swEndPoint.X, swEndPoint.Y, 0#, swEndPoint.X, swEndPoint.Y + dLength, 0#
'reset
swModel.SetDisplayWhenAdded True
swModel.SetAddToDB False
' Commit changes made to the sketch
swModel.InsertSketch2 True
Set aFlangeEdges(0) = swEdge
Set aSketchFeats(0) = swSketch
vFlangeEdges = aFlangeEdges
vSketchFeats = aSketchFeats
'create edge flange
Set swFeature = swModel.FeatureManager.InsertSheetMetalEdgeFlange2((vFlangeEdges), (vSketchFeats), 128, dAngle, 0.7 / 1000, swFlangePositionTypes_e.swFlangePositionTypeMaterialInside, dLength, swSheetMetalReliefTypes_e.swSheetMetalReliefNone, 0#, 0#, 0#, swFlangeDimTypes_e.swFlangeDimTypeInnerVirtualSharp, Nothing)
End Sub

How to change the color of a cylinder in VB programmatically

I have created a cylinder programmatically via vb on NX, the cylinder is successful, but unfortunately it doesn't change its color. Below is my code, could someone please tell me what's wrong with my code? Or is there any other method which I can change the color of my cylinder?
Thank you very much
Imports System
Imports NXOpen
Module Points_01
Sub Main()
Dim theSession As Session = Session.GetSession()
Dim workPart As Part = theSession.Parts.Work
Dim lw As ListingWindow = theSession.ListingWindow
lw.Open()
'create Point3d using the constructor
Dim myPt1 As New Point3d(0, 0, 0)
'create center point
Dim ptObj As Point
ptObj = workPart.Points.CreatePoint(myPt1)
ptObj.SetVisibility(SmartObject.VisibilityOption.Visible)
Dim myVector As Vector3d
'enter values for vector
myVector.X = (1)
myVector.Y = (2)
myVector.Z = (3)
'create offset
Dim myOffset As Offset
myOffset = workPart.Offsets.CreateOffset(ptObj.Coordinates, myVector, SmartObject.UpdateOption.WithinModeling)
'create new point offset from first point
Dim offsetPoint As Point
offsetPoint = workPart.Points.CreatePoint(myOffset, ptObj, SmartObject.UpdateOption.WithinModeling)
offsetPoint.RemoveParameters()
offsetPoint.SetVisibility(SmartObject.VisibilityOption.Visible)
lw.Close()
' Create circle
Dim curves As NXOpen.CurveCollection = workPart.Curves
Dim center As NXOpen.Point3d
center = New Point3d(0,0,0)
Dim pi as Double =System.Math.PI
Dim twopi As Double = 2*pi
Dim length As Double = 8
Dim axisX = New Vector3d(1,0,0)
Dim axisY = New Vector3d(0,1,0)
Dim circle = workPart.curves.CreateArc(center, axisX, axisY, length, 0, twopi)
Dim ctol = 0.0095 ' Chaining tolerance
Dim dtol = 0.01 ' Distance tolerance
Dim atol = 0.5 ' Angle tolerance
'Create a circular section
Dim circ As NXOpen.Section = workPart.Sections.CreateSection(ctol, dtol, atol)
Dim helpPoint As New NXOpen.Point3d(0,0,0)
Dim nullObj As NXOpen.NXObject = Nothing
Dim noChain As Boolean = False
Dim createMode As NXOpen.Section.Mode = Section.Mode.Create
' Create rules to add the circle to the section
Dim circl As NXOpen.CurveDumbRule = workPart.ScRuleFactory.CreateRuleBaseCurveDumb({circle})
circ.AddToSection({circl}, circle, nullObj, nullObj, helpPoint, createMode, noChain)
Dim builder = workPart.Features.CreateExtrudeBuilder(Nothing)
builder.Section = circ
'Define the direction of the Extrude
Dim origin As New NXOpen.Point3d(0,0,0)
Dim axisZ As New NXOpen.Vector3d(0,0,1)
Dim updateOption = SmartObject.UpdateOption.DontUpdate
builder.Direction = workPart.Directions.CreateDirection(origin, axisZ, updateOption)
builder.Limits.StartExtend.Value.RightHandSide = "0"
builder.Limits.EndExtend.Value.RightHandSide = "500"
Dim extrudeFeature As NXOpen.Features.Extrude = builder.CommitFeature
builder.Destroy
'Get the displayable object of the Extrude feature
Dim bodies As NXOpen.Body() = extrudeFeature.GetBodies
' Change its color
bodies(0).Color = 186 ' Usually red, by default
End Sub
End Module```

CATIA-VBA error: Function or interface marked restricted ... automation type not supported in Visual Basic

I've recorded a line creation in a VBA macro file, and it generated the following code:
Sub CATMain()
Dim partDocument1 As PartDocument
Set partDocument1 = CATIA.ActiveDocument
Dim part1 As Part
Set part1 = partDocument1.Part
Dim bodies1 As Bodies
Set bodies1 = part1.Bodies
Dim body1 As Body
Set body1 = bodies1.Item("PartBody")
Dim sketches1 As Sketches
Set sketches1 = body1.Sketches
Dim originElements1 As OriginElements
Set originElements1 = part1.OriginElements
Dim reference1 As Reference
Set reference1 = originElements1.PlaneYZ
Dim sketch1, sketch1Variant As Sketch *
Set sketch1 = sketches1.Add(reference1)
Dim arrayOfVariantOfDouble1(8)
arrayOfVariantOfDouble1(0) = 0#
...
arrayOfVariantOfDouble1(8) = 1#
Set sketch1Variant = sketch1
sketch1Variant.SetAbsoluteAxisData **
arrayOfVariantOfDouble1
part1.InWorkObject = sketch1
Dim factory2D1 As Factory2D
Set factory2D1 = sketch1.OpenEdition()
Dim geometricElements1 As GeometricElements
Set geometricElements1 = sketch1.GeometricElements
Dim axis2D1 As Axis2D
Set axis2D1 = geometricElements1.Item("AbsoluteAxis")
Dim line2D1 As Line2D
Set line2D1 = axis2D1.GetItem("HDirection")
line2D1.ReportName = 1
Dim line2D2 As Line2D
Set line2D2 = axis2D1.GetItem("VDirection")
line2D2.ReportName = 2
Dim point2D1 As Point2D
Set point2D1 = factory2D1.CreatePoint(21.285706, -30.501825)
point2D1.ReportName = 3
Dim point2D2 As Point2D
Set point2D2 = factory2D1.CreatePoint(112.826553, -68.875053)
point2D2.ReportName = 4
Dim line2D3 As Line2D
Set line2D3 = factory2D1.CreateLine(21.285706, -30.501825, 112.826553, -68.875053)
line2D3.ReportName = 5
line2D3.StartPoint = point2D1
line2D3.EndPoint = point2D2
sketch1.CloseEdition
part1.InWorkObject = body1
part1.Update
End Sub
Now
The issue is that when i run the code as is after recording I get the following error:
Error in loading dll.
Than I add sketch1Variant object at line * and run the code again.
This time I get the
"Function or interface marked restricted, or the function uses an automation type not supported in Visual Basic" error for line **.
I don't know what's wrong.
Any info is highly appreciated.
Thank you in advance.
The basic rule is this: When using VBA, any CATIA method which takes an array as an argument, or returns through an argument must be called on a variant object.
You have declared Sketch1Variant as Sketch. And SetAbsoluteAxisData takes an array as an argument.
What you want is this:
Dim Sketch1 as Sketch
Dim Sketch1Variant as Variant
(or just leave the "as variant" part off).
With this change you should be able to get past your problem.
In the future please do a web search first, because this is a VERY common question. coe.org is a good site to search.

Can't get sensible co-ordinates for note blocks

I've been trying to resurrect an existing drawing check macro, and want to find the co-ordinates of any note blocks on each sheet. I've been modifying code found here using the GetAttachPos method from this page, but for some reason any co-ordinates returned come back around (8.80942311664557E-03,2.24429295226372E-03).
I'm thinking that the problem is that I've missed a reference somewhere, but I'm not sure where. Although it's definitely finding the notes since it passes back their text. Anyway, here's the method I'm testing at the moment:
Sub Main()
Dim swApp As SldWorks.SldWorks
Set swApp = CreateObject("SldWorks.Application")
Dim NoteNumbersText As String
Dim NoteText As String
Dim NumberofSheets As Integer ' The number of sheets in this drawing
Dim NamesOfSheets As Variant ' Names of all of the sheets
Dim sheet As SldWorks.sheet ' The Sheet that we are working on
Dim LocalView As SldWorks.View ' Current View that we are looking at
Dim LocalNote As SldWorks.Note ' Current Note that we are looking at
Dim TextFormat As SldWorks.TextFormat ' Current text format object of a note
Dim Xpos As Double ' X, Y Z position on the drawing in Metres
Dim Ypos As Double
Dim SizeOfSheet As Double
Dim x As Integer ' general Loop Variables
Dim j As Integer
Dim k As Integer
Dim l As Integer
Dim vPosition As Variant
Dim vNote As Variant ' Single note
Dim swNote As SldWorks.Note ' Single Solidworks Note Object
Dim ThisAnnotation As SldWorks.Annotation
Dim swBlockInst As SldWorks.SketchBlockInstance
Dim swBlockDef As SldWorks.SketchBlockDefinition
Dim NumofNotes As Integer
Dim ArrayOfNotes() As NoteInfo
Dim LocalDrawingDoc As SldWorks.DrawingDoc ' Declared as an Object so that non Drawings can be detected!
Dim LocalPart As SldWorks.ModelDoc2 ' Declared as an Object so that non Drawings can be detected!
Dim strShtProp As Variant
Set LocalDrawingDoc = swApp.ActiveDoc
Set LocalPart = swApp.ActiveDoc
ReDim ArrayOfNotes(0)
' Get the sheet names and the number of them
NamesOfSheets = LocalDrawingDoc.GetSheetNames()
NumberofSheets = LocalDrawingDoc.GetSheetCount
' store this sheet name
Set sheet = LocalDrawingDoc.GetCurrentSheet()
strShtProp = sheet.GetProperties() ' get the sheet properties use much later for converting position into ref
SizeOfSheet = strShtProp(5)
Dim SwSketchMgr As SldWorks.SketchManager
Set SwSketchMgr = LocalDrawingDoc.SketchManager
Dim i As Integer
Dim vBlockDef As Variant
Dim vBlockInst As Variant
Dim strReturn As String
' Dim bret As Boolean
vBlockDef = SwSketchMgr.GetSketchBlockDefinitions
For x = NumberofSheets - 1 To 0 Step -1
If LocalDrawingDoc.GetCurrentSheet.GetName <> NamesOfSheets(x) Then LocalDrawingDoc.ActivateSheet NamesOfSheets(x)
Set LocalView = LocalDrawingDoc.GetFirstView
While Not LocalView Is Nothing
If Not IsEmpty(vBlockDef) Then
For i = 0 To UBound(vBlockDef)
Set swBlockDef = vBlockDef(i)
vBlockInst = swBlockDef.GetInstances
vNote = swBlockDef.GetNotes
If Not IsEmpty(vNote) Then
For j = 0 To UBound(vNote)
Set swNote = vNote(j)
NoteNumbersText = Trim(swNote.GetText)
If Left(NoteNumbersText, 1) = "n" And Len(NoteNumbersText) > 1 And Len(NoteNumbersText) < 4 Then
Set ThisAnnotation = swNote.GetAnnotation
'vPosition = swNote.GetAttachPos
vPosition = ThisAnnotation.GetPosition
Xpos = vPosition(0)
Ypos = vPosition(1)
Debug.Print ("Note " & NoteNumbersText & ": " & Xpos & "," & Ypos)
End If
Next j
End If
Next i
End If
Set LocalView = LocalView.GetNextView
Wend
Next x
End Sub
Turns out that SolidWorks is set up to return positions of blocks relative to the drawing view on which they're placed. Calling GetXForm for the view which they are placed on then provides a way of calculating the absolute position of each note.