获取随机选择颜色的值

Get value of the randomly chosen color

我有一个为零件或装配着色的宏。它随机选择颜色,然后将其应用于组件。我的问题是,我想获取随机选择的颜色的值,因为我想在其他子程序中使用该值,但我不知道如何获取它。有人可以帮我吗?这是我的代码。

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

请尝试下一种方式:

  1. 在标准模块顶部(在声明区域)将 vMatProp 声明为 Public 变量:
Public vMatProp as Variant
  1. 运行 您使用的代码,原样。 不要忘记从中删除声明!否则,它不会 return 错误,而是 仅将其值用于此(现有)过程

  2. 在任何其他 Sub 中使用它,因为它是...