Apply Material to a Part

Here’s a VBA code to apply material to an opened SolidWorks part file. This macro applies ‘AISI 304’ material from ‘Solidworks Materials.sldmat’ database to the active configuration of the active part file.

' Prerequisites:
' A part model should be open in Solidworks.
' The part model should be the active document in SolidWorks.

Sub main()
    
    'Declare Variables
    Dim swApp As SldWorks.SldWorks
    Dim swModel As SldWorks.ModelDoc2
    Dim swPart As SldWorks.PartDoc

    'Get Access to Solidworks
    Set swApp = Application.SldWorks

    ' Get Access to Model
    Set swModel = swApp.ActiveDoc
        
    ' Get Access to Part
    Set swPart = swModel
        
    'Add material
    swPart.SetMaterialPropertyName2 "", "SOLIDWORKS Materials.sldmat", "AISI 304"
    
End Sub

In order to apply a material to a part, a method named ‘SetMaterialPropertyName2’ is used. The following flowchart shows how we got access to this method in the above written code.

About the method – SetMaterialPropertyName2

As shown in the flowchart, this method is a member of ‘IPartDoc’ interface. Here’s the syntax for using this method:

Dim instance As IPartDoc
Dim ConfigName As System.String
Dim Database As System.String
Dim Name As System.String
 
instance.SetMaterialPropertyName2(ConfigName, Database, Name)

In order to execute this method we need to pass 3 parameters through it. These are:

  • ConfigName
  • Database
  • Name
ConfigName

ConfigName is a ‘string’ parameter and refers to the name of the configuration of the part to which the material should be applied. If an empty string is passed for this parameter, then the specified material is applied to the active configuration of the part.

Database

Database is a ‘string’ parameter and refers to the name of the material database from which contains the material to be applied. It is important to make sure that the folder for material database file is added to the file locations in SolidWorks settings. This can be checked by clicking on Tools > Options > System Options > File Locations > Material Databases.

The database parameter should include the material database file name and the .sldmat extension. For example:

“solidworks materials.sldmat”

We can also mention the full path of the database file, as shown below:

“C:\Program Files\SOLIDWORKS\lang\english\sldmaterials\solidworks materials.sldmat”

If an empty string is passed, then the default material database in SolidWorks will be used.

Name

Name is a ‘string’ parameter and refers to the name of the material that needs to be applied. If an empty string is passed for this parameter, then any applied material is removed from the part.