Solidworks macro doesn't run from stand alone .exe

Hi everyone,

Because I haven’t found a solution on the forums, I’ve decided to post this problem here:

As a part of my master’s thesis I want to automate a solidworks macro from outside SW. For this I have created a VB.net application (.exe). To start from, I’ve used the example macro found on this website.

When I run this macro inside solidworks, there is no problem, everything runs as it should.
But when I run the same macro through the stand alone .exe, SW gives an error : run-time error ‘9”, Subscript out of range ( on the namesCount-line) He doesn’t count the number of files in the assembly for some reason.

The strange thing is, if I  start my computer, the first time I run the macro from the .exe, it works, but after that the error appears.

Is there someone who knows the cause and hopefully a solution to this problem?

SW-macro code:

Sub main()

Set swApp = Application.SldWorks

' Open assembly

openFile = "C:\Program Files\SolidWorksCorp\SolidWorks\samples\tutorial\advdrawings\handle.sldasm"

Set swModelDoc = swApp.OpenDoc6(openFile, swDocASSEMBLY, swOpenDocOptions_Silent, "", errors, warnings)

Set swModelDocExt = swModelDoc.Extension

' Get Pack and Go object

Debug.Print "Pack and Go"

Set swPackAndGo = swModelDocExt.GetPackAndGo

' Get number of documents in assembly

namesCount = swPackAndGo.GetDocumentNamesCount()

VB.net (.exe)

Module Module1

    Sub Main()

        Dim app As SldWorks = CreateObject("SldWorks.Application")

        Dim mySolidworks() As Process

        mySolidworks = Process.GetProcessesByName("SLDWORKS")

        If app IsNot Nothing Then

            app.Visible = False

           

            app.RunMacro("C:\source\MHT-macro.swp", "Module150214", "main")

            'may have to kill SolidWorks

            mySolidworks = Process.GetProcessesByName("SLDWORKS")

            app.CloseAllDocuments(True)

            app.ExitApp()

            Try

                mySolidworks(0).Kill()

            Catch ex As Exception

            End Try

        End If

    End Sub

End Module

SolidworksApi macros