SOLIDWORKS: Insert a Part into an Assembly Using VBA

Hello

I'm new to VBA and I'd like to create a macro that creates an assembly and inserts a 1st part first.

I tried to record a macro, but it doesn't work!

There she is:

Dim swApp As ObjectDim Part As Object
Dim boolstatus As Boolean
Dim longstatus As Long, longwarnings As Long

Sub main()

Set swApp = Application.SldWorks

Set Part = swApp.NewDocument("C:\ProgramData\SolidWorks\SOLIDWORKS 2015\templates\Assemblage.asmdot", 0, 0, 0)
swApp.ActivateDoc2 "Assemblage1", False, longstatus
Set Part = swApp.ActiveDoc
Dim myModelView As Object
Set myModelView = Part.ActiveView
myModelView.FrameState = swWindowState_e.swWindowMaximized

boolstatus = Part.AddComponent("C:\Users\Me\Desktop\Folder\Part1.SLDPRT", 0, 0, 0)

End Sub

At first glance, the error seems to come from the line:

boolstatus = Part.AddComponent("C:\Users\Me\Desktop\Folder\Part1.SLDPRT", 0, 0, 0)

 

Could someone tell me where the problem comes from?

Thank you in advance.

Kind regards

 

Hello

First of all, beware of the macro recorder, it does not use the latest versions of the API methods.

For the AddComponent, look here, you'll see that this function allows you to add a component that is pre-loaded in Solidworks.

Kind regards

1 Like

Oh okay, so the only solution is to first open the part, insert it into the assembly and then close it? There is no other function than AddComponent?

Another question:

When I record macros, I often end up with variables such as boolstatus, longstatus, etc... Could someone explain to me what they are for? Reading the code I have the impression that these are variables that don't really have a specific purpose but that are used for everything and for nothing. Is that right?

Hello

The variables boolstatus, longstatus, etc... are not entirely useless, for example, for the AddComponent function, boolstatus is the return value of the method:

Function AddComponent(_

ByVal CompName As System.String, _

ByVal X As System.Double, _

ByVal Y As System.Double, _

ByVal Z As System.Double _

) As System.Boolean

 

Look at this side before jumping headlong into macros otherwise you risk getting lost quickly, and then a little reading on the Solidworks APIs that can be found here.

Kind regards

Hello

As mentioned in the previous message, these variables are used to store function return values.

When the function needs to return several values (error messages, result of the function such as when accessing custom properties) you must first create the variables and pass them by reference to the function to get the values.