Auto-Insert Active Part into New Assembly

Hey guys,

I'm trying to write a simple macro that, when run, takes the active document and places it 'origin-on-origin' as the base component in a newly created assembly.

I think I'm calling AddComponent4 improperly. When I run this, I get 'Object variable ... not set' message.

Any idea what I may be doing wrong here?

Thanks,
Sean

Dim swApp As SldWorks.SldWorks

Dim swModel As SldWorks.ModelDoc2

Dim swAssy As AssemblyDoc

Dim modPath As String

Dim swComponent As SldWorks.Component2

Sub main()

    Set swApp = Application.SldWorks

    Set swModel = swApp.ActiveDoc

    modPath = swModel.GetTitle

    Debug.Print "Path name equals " & modPath; "."

    swApp.NewAssembly

    Set swComponent = swAssy.AddComponent4(modPath, 0, 0, 0, 0)

End Sub

SolidworksApi macros
Answers 5
DG
DG 2014-05-11 Best Answer

Try this one:

<p>Dim swApp As SldWorks.SldWorks</p><p>Dim swModel As SldWorks.ModelDoc2</p><p>Dim swAssy As AssemblyDoc</p><p>Dim modPath As String</p><p>Dim swComponent As SldWorks.Component2</p><p>Sub main()</p><p>    Set swApp = Application.SldWorks</p><p>    Set swModel = swApp.ActiveDoc</p><p></p><p>    modPath = swModel.GetTitle</p><p>    Debug.Print "Path name equals " & modPath; "."</p><p>    swApp.NewAssembly</p><p>    Set swAssy = swApp.ActiveDoc</p><p>    Set swComponent = swAssy.AddComponent2(modPath, 0, 0, 0)</p><p>    swAssy.ForceRebuild</p><p>    </p><p>  End Sub</p>
SF
SF 2014-05-12

Deepak,

Using AddComponent2 produced much better results.

Do you use this, as opposed to the other comparable calls, due to its simplicity and ease of use?

Thanks,

Sean

DG
DG 2014-05-12
<p><span style="font-size: 10pt;">due to its simplicity and ease of use?</span></p>

Yes. Though it is obsolete now but worked fine.

MM
MM 2014-05-14

I know Deepak provided an answer but I thought I might point out where your code may have gone wrong.

<p></p><p>Dim swApp As SldWorks.SldWorks</p><p>Dim swModel As SldWorks.ModelDoc2</p><p>Dim swAssy As AssemblyDoc</p><p>Dim modPath As String</p><p>Dim swComponent As SldWorks.Component2</p><p></p><p style="min-height: 8pt; padding: 0px;"> Sub main()</p><p>    Set swApp = Application.SldWorks</p><p>    Set swModel = swApp.ActiveDoc</p><p></p><p>    modPath = swModel.GetTitle</p><p></p><p>    Debug.Print "Path name equals " & modPath; "."</p><p></p><p>    <em style="color: #ff0000;">swApp.NewAssembly</em></p><p>    <em style="color: #ff0000;"><strong>Set swComponent = swAssy.AddComponent4(modPath, 0, 0, 0, 0)</strong></em></p><p></p><p>End Sub</p>

Perhaps you should of had:

Set swAssy = swApp.NewAssembly

Set swComponent = swAssy.AddComponent4(modPath, 0, 0, 0, 0)

I think that is why it failed. You never set the "swAssy" object to anything.

SF
SF 2014-05-14

Matt,

Thank you! I missed that: you're right.