Code:
Transform Sketch to Model Example (VB)
When a sketch point is created, its x, y, and z location values are in relation to the sketch origin. Using the MathUtility object, it is possible to display the sketch point’s coordinates in relation to the model origin. Obtain the MathUtility object from the current model document.
Select a sketch that contains the points whose coordinates are to be modified.
Call Sketch::GetSketchPoints to fill a VARIANT array with all of the points in the sketch.
Build a coordinate array by filling the cells of a length 3 array with the x, y, and z value of a sketch point from the VARIANT array.
Create a new MathPoint from the MathUtility object, providing the coordinate array for the location of the MathPoint.
Get the model-to-sketch transform for this sketch. Calling MathTransform::Inverse provides a MathTransform from the sketch coordinates to the model coordinates. The MathPoint is then moved into the model coordinates by calling MathPoint::MulitplyTransform(MathTransform).
Implementing this in code is fairly straightforward:
Option Explicit
Dim swApp As SldWorks.SldWorks
Dim selMgr As SldWorks.SelectionMgr
Dim Model As SldWorks.ModelDoc2
Dim SketchPoints As Variant
Dim SketchFeature As SldWorks.feature
Dim PointCoords(2) As Double
Dim MathUtil As SldWorks.MathUtility
Dim MathTrans As SldWorks.MathTransform
Dim MathP As SldWorks.MathPoint
Dim ModelSketchTransform As Variant
Sub main()
'Connect the program to SolidWorks
Set swApp = CreateObject("SldWorks.Application")
Set Model = swApp.ActiveDoc
'Prepare the MathUtility
Set MathUtil = swApp.GetMathUtility
'Get the SelectionMgr
Set selMgr = Model.SelectionManager
'Get the sketch from the SelectionMgr
Set SketchFeature = selMgr.GetSelectedObject5(1)
Set SketchFeature = SketchFeature.GetSpecificFeature2
'Get the sketch points
SketchPoints = SketchFeature.GetSketchPoints
'Build a coordinate array from the first point in the sketch
PointCoords(0) = SketchPoints(0).x
PointCoords(1) = SketchPoints(0).y
PointCoords(2) = SketchPoints(0).z
'Create the new MathPoint from the sketch point data.
'MathP refers to the point location in the sketch coordinates
Set MathP = MathUtil.CreatePoint(PointCoords)
'Display the point coordinates in relation to the sketch origin
SketchPoints = MathP.ArrayData
MsgBox SketchPoints(0) & ", " & SketchPoints(1) & ", " & SketchPoints(2)
'Get the model-to-sketch transform for this sketch
Set MathTrans = SketchFeature.ModelToSketchTransform
'Get the inversion of the transform
Set MathTrans = MathTrans.Inverse
'Multiply the point by the inverse transform
'MathP now refers to the point location in the model coordinates
Set MathP = MathP.MultiplyTransform(MathTrans)
'Display the point coordinates in relation to the model origin
SketchPoints = MathP.ArrayData
MsgBox SketchPoints(0) & ", " & SketchPoints(1) & ", " & SketchPoints(2)
End Sub