Set Material Example (VBA)
This example shows how to get the names of the material schema, material
databases, and bodies in a part document. This example also shows how
to apply a SolidWorks Material to all of the bodies in a part document.
'-----------------------------
' Preconditions: Specified document exists.
'
' Postconditions: The material ABS
PC from the
' SolidWorks
Material database is applied to all
' bodies
in the open part document.
'
' NOTE: Because the part document is intended
' for
use with a SolidWorks online tutorial,
' do
save any changes when closing the
' the
document.
'------------------------------
Option Explicit
Sub main()
Dim
swApp As
SldWorks.SldWorks
Dim
swModel As
SldWorks.ModelDoc2
Dim
swPart As
SldWorks.PartDoc
Dim
swBody As
SldWorks.Body2
Dim
errors As
Long
Dim
warnings As
Long
Dim
vMatDBarr As
Variant
Dim
vMatDB As
Variant
Dim
Bodies As
Variant
Dim
BodyMaterialError As
Long
Dim
sMatName As
String
Dim
sMatDB As
String
Dim
itr As
Long
Set
swApp = Application.SldWorks
'
Open the document
Set
swModel = swApp.OpenDoc6("c:\Program
Files\SolidWorks Corp\SolidWorks\samples\tutorial\multibody\multi_inter.sldprt",
swDocPART, swOpenDocOptions_Silent, "", errors, warnings)
Set
swPart = swModel
'
Get the material schema and names
'
of available materials databases
vMatDBarr
= swApp.GetMaterialDatabases
Debug.Print
"Material schema pathname = " & swApp.GetMaterialSchemaPathName
For
Each vMatDB In vMatDBarr
Debug.Print
" Material
database: " & vMatDB
Next
Debug.Print
""
Bodies
= swPart.GetBodies2(swAllBodies,
False)
For
itr = 0 To UBound(Bodies)
Set
swBody = Bodies(itr)
'
Get the name of the body
Debug.Print
swBody.Name
'
Set the SolidWorks material for that body
'
Use either of the following statements
'
when the only configuration is the Default
'
configuration
'BodyMaterialError
= swBody.SetMaterialProperty("",
"solidworks materials.sldmat", "ABS PC")
BodyMaterialError
= swBody.SetMaterialProperty("",
"", "ABS PC")
'
Get the names of the body's material and the
'
database to which it belongs
sMatName
= swBody.GetMaterialPropertyName("",
sMatDB)
If
sMatName = "" Then
Debug.Print
("Body " & itr & "'s material name: No material
applied")
Else
Debug.Print
("Body " & itr & "'s material name: " &
sMatName)
Debug.Print
("Body " & itr & "'s material database: "
& sMatDB)
Debug.Print
(" ")
End
If
Next
itr
End Sub