Files
Lesson 3.4 homework part A solution
Code
'Homework 3.4a
'Write a macro that prints the screen the number of objects selected to the immediate window. _
Also print the number of faces, edges, and vertices that were selected. Finally, if a _
selected object is a feature, print the name and visibility to the immediate window. Also _
include error handling in the event that nothing was selected. Optionally, include error _
handling in the even that no document is open.
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim swSelMgr As SldWorks.SelectionMgr
Dim swFeat As SldWorks.Feature
Dim intFaceCount As Integer
Dim intEdgeCount As Integer
Dim intVertexCount As Integer
Dim i As Integer
Sub main()
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
'make sure a document is open; the type of document does not matter since the selection _
manager works in parts, assemblies, and drawings
If swModel Is Nothing Then
MsgBox "Please open a document."
End
End If
Set swSelMgr = swModel.SelectionManager
intFaceCount = 0
intEdgeCount = 0
intVertexCount = 0
'error handling in the event that nothing was selected
If swSelMgr.GetSelectedObjectCount2(-1) = 0 Then
MsgBox "Please select some objects before running macro."
End
End If
Debug.Print "# selected objects: " & swSelMgr.GetSelectedObjectCount2(-1)
'Loop through all of the selections. Don't forget that the counter must start at 1, not 0
For i = 1 To swSelMgr.GetSelectedObjectCount2(-1)
If swSelMgr.GetSelectedObjectType3(i, -1) = swSelectType_e.swSelFACES Then
intFaceCount = intFaceCount + 1
ElseIf swSelMgr.GetSelectedObjectType3(i, -1) = swSelectType_e.swSelEDGES Then
intEdgeCount = intEdgeCount + 1
ElseIf swSelMgr.GetSelectedObjectType3(i, -1) = swSelectType_e.swSelVERTICES Then
intVertexCount = intVertexCount + 1
ElseIf swSelMgr.GetSelectedObjectType3(i, -1) = swSelectType_e.swSelBODYFEATURES Then
Set swFeat = swSelMgr.GetSelectedObject6(i, -1)
Debug.Print " Feature name: " & swFeat.Name
'IFeature::Visible returns a 1 for hidden and 2 for shown
If swFeat.Visible = 1 Then
Debug.Print " Feature visibility: Hidden"
Else
Debug.Print " Feature visibility: Shown"
End If
End If
Next i
Debug.Print " # of faces: " & intFaceCount
Debug.Print " # of edges: " & intEdgeCount
Debug.Print " # of vertices: " & intVertexCount
End Sub