MACRO LIBRARY

Change selected body's material in all configurations

Free public access. No account or subscription required.

Files

Change selected body's material

Code

Module: mMain

'Demonstrates how to change the selected body's material in all configurations.
'Derived configurations are skipped.
    
'Preconditions:
'   1. Body is selected in feature manager tree.
'   2. Material name and database path are specified in constants. Note that you
'      can set the db path to Empty if you want to use the standard SolidWorks
'      database. If you use a custom database, be sure to first add the folder
'      to System Options-->File Locations-->Material Databases.
    
'Written by Keith Rice
'CADSharp LLC
'www.cadsharp.com
    
Option Explicit
    
Const MAT_NAME As String = "Plain Carbon Steel"
Const MAT_DB_PATH As String = Empty
    
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim swSelMgr As SldWorks.SelectionMgr
Dim swPart As SldWorks.PartDoc
Dim swBody As SldWorks.Body2
Dim swConfig As SldWorks.Configuration
Dim vConfigName As Variant
Dim strBodyName As String
Dim strBodyType As String
Dim i As Integer
    
Sub main()
    Set swApp = Application.SldWorks
    Set swModel = swApp.ActiveDoc
    Set swSelMgr = swModel.SelectionManager
    Set swPart = swModel
    
    Set swBody = swSelMgr.GetSelectedObject6(1, -1)
    strBodyName = swBody.Name
    
    Select Case swBody.GetType
        Case swSolidBody
            strBodyType = "SOLIDBODY"
        Case swSheetBody
            strBodyType = "SURFACEBODY"
        Case Else
            swApp.SendMsgToUser "Unrecognized body type."
            Exit Sub
    End Select
    
    vConfigName = swModel.GetConfigurationNames
    For i = 0 To UBound(vConfigName)
        Set swConfig = swModel.GetConfigurationByName(vConfigName(i))
        If swConfig.IsDerived = False Then
        
            'The next three lines are crucial. For IBody2::SetMaterialProperty and _
            IBody2::GetMaterialPropertyName to work, the desired configuration _
            must be active and the body must be a selected. The IBody2 pointer _
            in the current configuration should be obtained, otherwise sucess _
            is sporadic.
            
            swModel.ShowConfiguration2 vConfigName(i)
            swModel.Extension.SelectByID2 _
                strBodyName, strBodyType, 0, 0, 0, False, 0, Nothing, 0
            Set swBody = swSelMgr.GetSelectedObject6(1, -1)
            
            swBody.SetMaterialProperty vConfigName(i), MAT_DB_PATH, MAT_NAME
            Debug.Print "Body: " & strBodyName
            Debug.Print vbTab & "Material: " & _
                swBody.GetMaterialPropertyName(Empty, Empty)
        
        End If
    Next i
End Sub