vbasolidworkssolidworksapi

Get value of the randomly chosen color


I have a macro that colors the part or assembly. It randomly chooses the color and then apply it to the component. My problem is, I want to get the value of the randomly chosen color because I want that value in other sub, but I dont know how to get it. Could someone help me with this? Heres my code.

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
  If swModel.GetType = swDocPART Then
    vElementArr = swModel.GetBodies2(swAllBodies, 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.MaterialPropertyValues2 = vMatProp
    Next
    
  ElseIf swModel.GetType = swDocASSEMBLY Then
    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
    
  ElseIf swModel.GetType = swDocDRAWING Then
    MsgBox ("You can only apply random colors to part bodies or assembly components.")
    Exit Sub
    
  End If

 'Redraw to see new color
  swModel.GraphicsRedraw2

End Sub

Solution

  • Please, try the next way:

    1. Declare vMatProp as a Public variable on top of a standard module (in the declarations area):
    Public vMatProp as Variant
    
    1. Run the code you use, as it is. Do not forget to delete the declaration from it! Otherwise, it will not return an error, but use its value only for this (existing) procedure.

    2. Use it in any other Sub, as it is...