I have this code that automatically colors all assembly components with random color. I asked a different question with this code before but this time, I want to ask if anyone could help To make this code colors only the selected assembly component? I hope someone can help me with this, I am still learning in API. Please see code below.
Dim swApp As Object
Dim Part As Object
Dim boolstatus As Boolean
Dim longstatus As Long, longwarnings As Long
Public Sub ColorMacro1()
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim swElement As Object
Dim vElementArr As Variant
Dim vElement As Variant
Dim vMatProp As Variant
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
vMatProp = swModel.MaterialPropertyValues
'Get all elements
vElementArr = swModel.GetComponents(False)
For Each vElement In vElementArr
Set swElement = vElement
Randomize
vMatProp(0) = Rnd 'Red
vMatProp(1) = Rnd 'Green
vMatProp(2) = Rnd 'Blue
vMatProp(3) = Rnd / 2 + 0.5 'Ambient
vMatProp(4) = Rnd / 2 + 0.5 'Diffuse
vMatProp(5) = Rnd 'Specular
vMatProp(6) = Rnd * 0.9 + 0.1 'Shininess
swElement.MaterialPropertyValues = vMatProp
Next
'Redraw to see new color
swModel.GraphicsRedraw2
End Sub
You can get the selected components with GetSelectedObjectsComponent4 like so:
Option Explicit
Public Sub ColorMacro1()
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim vMatProp As Variant
Dim swSelMgr As SldWorks.SelectionMgr
Dim swComp As SldWorks.Component2
Dim Count As Integer
Dim i As Integer
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
Set swSelMgr = swModel.SelectionManager
Count = swSelMgr.GetSelectedObjectCount2(0)
If Count = 0 Then MsgBox "No Components selected": Exit Sub
vMatProp = swModel.MaterialPropertyValues
For i = 1 To Count
Set swComp = swSelMgr.GetSelectedObjectsComponent4(i, 0)
Randomize
vMatProp(0) = Rnd 'Red
vMatProp(1) = Rnd 'Green
vMatProp(2) = Rnd 'Blue
vMatProp(3) = Rnd / 2 + 0.5 'Ambient
vMatProp(4) = Rnd / 2 + 0.5 'Diffuse
vMatProp(5) = Rnd 'Specular
vMatProp(6) = Rnd * 0.9 + 0.1 'Shininess
swComp.MaterialPropertyValues = vMatProp
Next
swModel.GraphicsRedraw2
End Sub