Files
Get longest sketch segment in a sketch
Code
Module:
'Demonstrates how to get the longest sketch segment in a sketch and its length.
'Preconditions: Feature is selected.
'Results: Longest sketch segment of specified type is selected and its length is _
printed to the immediate window.
'Notes:
'-Use an argument of -1 for segmentType to search all sketch segment types.
'Written by Keith Rice
'CADSharp LLC
'www.cadsharp.com
Sub main()
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim swSelMgr As SldWorks.SelectionMgr
Dim swFeat As SldWorks.Feature
Dim swSkSeg As SldWorks.SketchSegment
Dim dblLength As Double
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
Set swSelMgr = swModel.SelectionManager
Set swFeat = swSelMgr.GetSelectedObject6(1, -1)
Set swSkSeg = GetLongestSketchSegment(swFeat, -1, False, dblLength)
If swSkSeg Is Nothing Then
Debug.Print "No sketch segment found"
Else
swSkSeg.Select False
Debug.Print Round(dblLength, 6) & "m"
End If
End Sub
Private Function GetLongestSketchSegment(swFeat As SldWorks.Feature, _
segmentType As swSketchSegments_e, isConstruction As Boolean, _
ByRef length As Double) As SldWorks.SketchSegment
length = 0
'If ISketch was not passed in for the first argument then we need to _
find the parent sketch. The wrong sketch might be returned for _
features that have multiple parent sketches, in which case it is _
better to pass in the desired ISketch pointer directly.
Dim swSketch As SldWorks.Sketch
If swFeat.GetSpecificFeature2 Is Nothing Then
Set swSketch = GetBaseSketch(swFeat)
ElseIf Not TypeOf swFeat.GetSpecificFeature2 Is SldWorks.Sketch Then
Set swSketch = GetBaseSketch(swFeat)
Else
Set swSketch = swFeat.GetSpecificFeature2
End If
Dim swSkSeg As SldWorks.SketchSegment
Dim vSkSegs As Variant
vSkSegs = swSketch.GetSketchSegments
If IsEmpty(vSkSegs) Then
Set GetLongestSketchSegment = Nothing
Exit Function
End If
For i = 0 To UBound(vSkSegs)
Set swSkSeg = vSkSegs(i)
If swSkSeg.ConstructionGeometry <> isConstruction Then GoTo Skip
If segmentType <> -1 And segmentType <> swSkSeg.GetType Then GoTo Skip
If swSkSeg.GetLength > length Then
Set GetLongestSketchSegment = swSkSeg
length = swSkSeg.GetLength
End If
Skip:
Next i
End Function
Private Function GetBaseSketch(swFeat As SldWorks.Feature) As SldWorks.Sketch
Dim vParents As Variant
vParents = swFeat.GetParents
If IsEmpty(vParents) Then
Set GetBaseSketch = Nothing
Exit Function
End If
Dim swParentFeat As SldWorks.Feature
Dim i As Integer
For i = 0 To UBound(vParents)
Set swParentFeat = vParents(i)
If swParentFeat.GetTypeName = "ProfileFeature" Then
Set GetBaseSketch = swParentFeat.GetSpecificFeature2
Exit Function
End If
Next i
If swParentFeat Is Nothing Then Set GetBaseSketch = Nothing
End Function