vbasolidworkssolidworksapi

Mismatch error in VBA macro code (.ImportPart)


Here is my code to make a SW macro which is able to open one by one .sldprt files from a folder and add another file (BoumdingBox) in each opened file.

The mismatch error is in line : Set objModel = objModel.InsertPart(objModel, 0)

I don't know how to resolve it, I am a beginner.

Thanks for your help


Sub OpenSldprtFiles()
    Dim strPath As String
    Dim strFile As String
    Dim objSW As SldWorks.SldWorks
    Dim objModel As SldWorks.ModelDoc2
    
    Set objSW = Application.SldWorks
    
    'Specify the folder path here
    strPath = "C:\Users\emilien.petit\Desktop\VolumeCalculation\Components\"
    
    'Loop through all the files in the folder
    strFile = Dir(strPath & "*.sldprt")
    Do While strFile <> ""
        'Open the file
        Set objModel = objSW.OpenDoc6(strPath & strFile, swDocPART, swOpenDocOptions_Silent, "", 0, 0)
        
        'Insert the new part
        Dim objPart As SldWorks.PartDoc
        Set objPart = objSW.NewDocument("C:\Users\emilien.petit\Desktop\VolumeCalculation\BoundingBox.SLDPRT", 0, 0, 0)
        If objPart.GetType = swDocPART Then
            Set objModel = objModel.InsertPart(objModel, 0)
        End If
        
        'Save the file as a part
        Dim strNewName As String
        strNewName = Replace(strFile, ".sldprt", "_new.sldprt")
        objSW.ActiveDoc.SaveAs3 "C:\Users\emilien.petit\Desktop\VolumeCalculation\" & strNewName, swSaveAsCurrentVersion, swSaveAsOptions_Silent, Nothing, Nothing, Nothing
        
        'Close the file
        objSW.CloseDoc (strPath & strFile)
        
        'Get the next file name
        strFile = Dir()
    Loop
    
End Sub

Need help to correct the error


Solution

  • According to SOLIDWORKS API documentation InsertPart method does exist for ModelDoc2 if it has type PartDoc, but it requires filename, not a PartDoc parameter. I suppose this is what is causing type mismatch.

    So I suggest you try adding a part like this:

    Call objModel.InsertPart("C:\Users\emilien.petit\Desktop\VolumeCalculation\BoundingBox.SLDPRT", /*three bool options that you want for import*/)