首页 > 解决方案 > 获取随机选择的颜色的值

问题描述

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

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

标签: vbasolidworkssolidworksapi

解决方案


请尝试下一个方法:

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

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


推荐阅读