How do I get a solidworks simulation name in visual basic for use in a macro?

65 views Asked by At

I want to automate taking snips of FEA results for reports and record keeping. I am trying to save as a PNG with the file name changing to match the Simulation Study name and the type of result I am looking at: Stress, Displacement, or Factor of Safety. I have the code to save a PNG in a designated location but I do not know how to query the name of the study or results through the macro.

I have the save as PNG macro working and I just need the code to pull the simulation and results names so I can tag it onto the end of the save as naming code.

1

There are 1 answers

0
solidWorking On

To get a Solidworks Simulation Name use the Name Property (ICWStudy) as documented here.

To get acess the study results use the Results Property (ICWStudy) as documented here.

Bellow you can find VBA code.

Option Explicit

Sub main()

    Dim SwApp           As SldWorks.SldWorks
    Dim COSMOSWORKS      As CosmosWorksLib.COSMOSWORKS
    Dim CWAddinCallBack  As CosmosWorksLib.CWAddinCallBack
    Dim ActDoc           As CosmosWorksLib.CWModelDoc
    Dim StudyMngr        As CosmosWorksLib.CWStudyManager
    Dim Study            As CosmosWorksLib.CWStudy
    Dim activeStudyIndex As Integer
    Dim CWResult         As CosmosWorksLib.CWResults
    Dim errorCode        As Long
    Dim stress           As Variant
    Dim nodeMin          As Integer
    Dim nodeMax          As Integer
    Dim stressMin        As Variant
    Dim stressMax        As Variant

    'Connect to SOLIDWORKS
    Set SwApp = Application.SldWorks
    If SwApp Is Nothing Then Exit Sub

    'Add-in callback
    Set CWAddinCallBack = SwApp.GetAddInObject("SldWorks.Simulation")
    Set COSMOSWORKS = CWAddinCallBack.COSMOSWORKS

    'Get active document
    Set ActDoc = COSMOSWORKS.ActiveDoc()

    'Get the active study
    Set StudyMngr = ActDoc.StudyManager()
    activeStudyIndex = StudyMngr.ActiveStudy

    Set Study = StudyMngr.GetStudy(activeStudyIndex)

    'Print the name of the study to the immediate window
    Debug.Print Study.Name


    'Get the results
    Set CWResult = Study.Results
    If CWResult Is Nothing Then Exit Sub

    'Get the stress results
    stress = CWResult.GetMinMaxStress(0, 0, 1, Nothing, 0, errorCode)
    
    'Print the stress results to the immediate window
    nodeMin = stress(0)
    stressMin = stress(1)
    nodeMax = stress(2)
    stressMax = stress(3)

    Debug.Print nodeMin
    Debug.Print stressMin
    Debug.Print nodeMax
    Debug.Print stressMax

End Sub

Tested it in a part document with only one study called Test Study and it get correctly printed the name and the stress results to immediate window.

Make sure you set reference to Solidworks Simulation 20## type library. It's not default.