Announcements
Attention for Customers without Multi-Factor Authentication or Single Sign-On - OTP Verification rolls out April 2025. Read all about it here.
WCrihfield
in reply to: utm007

Here is the corrected full code again, since I made so many hasty mistakes the first time.  This time I created a material by that name, then tested it out and fixed the code properly so that it worked in my tests.

Sub ChangeMaterial()
    If ThisApplication.ActiveDocumentType <> kPartDocumentObject Then
        Call MsgBox("This VBA macro only works on Parts.", vbCritical, "Wrong Document Type")
        Exit Sub
    End If
    Dim pDoc As PartDocument
    Set pDoc = ThisApplication.ActiveDocument
    Dim oMaterialDisplayName As String
    oMaterialDisplayName = "TestMaterial"
    Dim oMyMaterial As MaterialAsset
    Dim oMaterial As MaterialAsset
    For Each oMaterial In pDoc.MaterialAssets
        If oMaterial.DisplayName = oMaterialDisplayName Then
            Set oMyMaterial = oMaterial
        End If
    Next
    If oMyMaterial Is Nothing Then
        For Each oMaterial In ThisApplication.ActiveMaterialLibrary.MaterialAssets
            If oMaterial.DisplayName = oMaterialDisplayName Then
                Set oMyMaterial = oMaterial.CopyTo(pDoc)
            End If
        Next
    End If
    If oMyMaterial Is Nothing Then
        Call MsgBox("The specified material was not found.", vbCritical, "")
        Exit Sub
    End If
    pDoc.ActiveMaterial = oMyMaterial
End Sub

Wesley Crihfield

EESignature

(Not an Autodesk Employee)