Run a macro during a recording

Hello, I use this macro to display the title of a Solidworks document in windows explorer. I wanted to know if it was possible to activate the macro during each recording (without user intervention)? from what I understand, an add-in would be the best solution, but since I'm struggling with VS Studio, I'm looking for an alternative. Thank you

Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim propMgr As CustomPropertyManager
Dim titleValue As String
Dim resolved As String
Dim wasResolved As Boolean

Sub main()
    Set swApp = Application.SldWorks
    Set swModel = swApp.ActiveDoc
    If swModel Is Nothing Then
        MsgBox "No document is open!"
        Exit Sub
    End If

    ' Access the custom property manager
    Set propMgr = swModel.Extension.CustomPropertyManager("")

    ' Read current value of custom property "Title"
    wasResolved = propMgr.Get4("Title", False, resolved, titleValue)
    
    If titleValue = "" Then
        MsgBox "Custom property 'Title' is empty!"
        Exit Sub
    End If

    ' Copy to Summary Info Title
    swModel.SummaryInfo(swSumInfoTitle) = titleValue

    ' Optional: read back to verify
    MsgBox "Summary Info Title set to: " & swModel.SummaryInfo(swSumInfoTitle)
End Sub

Hello and welcome;

What exactly do you mean by:

It's not very clear...

And there are some essential pieces of information missing:
The Solidworks Version
The scope of the macro (all Solidworks documents, only parts, parts and assemblies, drawings...?)

What I understand:
In your macro, you extract the value of the custom " Title " property from an open SolidWorks document, and then place that value in the Title field of the document's summary information, checking for no no document or empty property errors.

(Note: I advise you not to use the same property (the Property Name) several times for different variables... (here " Title " for Custom Properties and " Title " for Windows Summary properties (tab: Summary in the information summary of the Solidworks document)

I suggest you adapt your macro so that it works on all the files in a given directory:

It's up to you to modify the value in:
folderPath = "C:\Path\To\Folder"

Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim propMgr As CustomPropertyManager
Dim titleValue As String
Dim resolved As String
Dim wasResolved As Boolean
Dim filePath As String
Dim folderPath As String

Sub main()
    Set swApp = Application.SldWorks

    ' Modifier ici pour mettre le chemin du dossier
    folderPath = "C:\Chemin\Vers\Le\Dossier\"
    
    filePath = Dir(folderPath & "*.sld*") ' Trouve les fichiers .sldprt, .sldasm, .slddrw

    Do While filePath <> ""
        ' Ouvre le document
        Set swModel = swApp.OpenDoc6(folderPath & filePath, _
                                     GetDocType(folderPath & filePath), _
                                     0, "", 0, 0)

        If Not swModel Is Nothing Then

            Set propMgr = swModel.Extension.CustomPropertyManager("")
            wasResolved = propMgr.Get4("Title", False, resolved, titleValue)

            If titleValue <> "" Then
                swModel.SummaryInfo(swSumInfoTitle) = titleValue
                swModel.Save
            End If

            swApp.CloseDoc swModel.GetTitle
        Else
            MsgBox "Impossible d'ouvrir : " & filePath
        End If

        filePath = Dir() ' Passe au fichier suivant
    Loop

    MsgBox "Traitement terminé."
End Sub

' Fonction utilitaire pour déterminer le type de document selon l'extension
Function GetDocType(fileName As String) As Long
    Dim ext As String
    ext = LCase$(Mid$(fileName, InStrRev(fileName, ".") + 1))
    Select Case ext
        Case "sldprt"
            GetDocType = 1 ' pièce
        Case "sldasm"
            GetDocType = 2 ' assemblage
        Case "slddrw"
            GetDocType = 3 ' mise en plan
        Case Else
            GetDocType = 0 ' inconnu
    End Select
End Function

Otherwise the subject has already been discussed here:
https://forum.mycad.visiativ.com/t/copier-proprietes-personnalisees-vers-les-proprietes-du-fichiers/108809?lang=en

But it's bothering for not much:
=> It is possible to use the Solidworks property manager to duplicate a variable to the Summary info.
https://help.solidworks.com/2022/french/SolidWorks/sldworks/HelpViewerDS.aspx?version=2022&prod=SolidWorks&lang=french&path=sldworks%2Fc_file_properties.htm&id=5fb9c079433c46d7961143b30be81132

=> it's easier with MyCadTools such as Smartproperties or in the processing station with the Integration or batchProperties tools.

1 Like

Hello, thank you for the answer and the links (very useful).

My goal is not to execute the macro on each part record (assembly, part or drawing) but rather to retrieve the value of the property named Title and display it on windows explorer as on this capture on each record, hence the remark on the fact that the macro is not the best solution in this case since it has to be executed each time.

on Windows Explorer

and on SolidWorks

I use SW 23 and SW24, I hope to invest in an SW25 version soon

Is it possible, for example, to automatically launch the macro, during a recording (assembly, drawing or part) without user intervention? It seems to me that this is possible with add-ins but not safe for VBA macros.

Hello
It's possible with vba but you have to modify the shortcut launching SW so that the macro runs once SW is opened.
You can intercept actions in SW but you have to cement the code and its exit doors to avoid ending up with behaviors blocking the use.
Another solution is to create a recording macro that replaces the SW recording icon and put the Ctrl+S shortcut on it so that it is totally transparent to the user.

3 Likes

Hello, thank you for the answer.

I've tried both methods and they all work great.

Just one last question, I'd like to try to create the add-in using VS. I have the code, create the dll but the add-in is not displayed on SolidWorks.

Bonjour;
Il faut probablement charger l’add-in via les compléments Solidworks.
Utiliser la méthode ISldWorks::LoadAddIn en passant le nom de l’add-in
puis
Après avoir chargé l’add-in, utilisez ISldWorks::GetAddInObject

pour une documentation plus globale sur la creation d’add-in:

il devrait maintenant etre accessible depuis:
image

Si le code est bien realisé, il devrait etre accessible ici:
image

Serait-il possible de nous fournir le code réalisé ?

Thank you for the documents.

I tried to redo Creating VB.NET add-in for SOLIDWORKS using API but I just have SolidWorks which is open when I launch the code without the Hello World and the add-in is not present in the add-ins menu.

Bonjour;

Extrait de l’aide Solidworks:

What does the add-in have to do?

The add-in DLL must be created as a COM Server and it must:

  1. Implement a co-creatable object that supports SwAddin.
  2. During installation call:

Register the add-in’s CLSID in HKEY_LOCAL_MACHINE\SOFTWARE\SOLIDWORKS\AddIns and set the following registry keys:

  • Default to 1 or 0, where 1 enables the add-in in the add-in manager so that it loads when the user starts the SOLIDWORKS software.
  • Description to a text description of the add-in that is displayed in the add-in manager.
  • Title to a text title of the description that is displayed in the add-in manager.
  1. Define event handlers as needed.

In its implementation of ISwAddin::ConnectToSW, the add-in can:

  1. Call ISldWorks::SetAddinCallbackInfo and pass the instance handle of the add-in and the object that supports the callback methods. The SOLIDWORKS software holds onto this object and makes callbacks.
  2. Call ISldWorks::AddMenuItem3 and pass the callback method associated with the menu item.
  3. Call ISldWorks::AddToolbar4 and pass the callback method associated with the toolbar button.

on en parle ici aussi:

et un autre exemple de code ici:

Dans cet exemple la ligne qui t’intéresse est la création de la clef dans le base de registre pour l’identification de l’add-in dans le menu Solidworks:
Dim keyname As String = « SOFTWARE\SolidWorks\Addins{ » + t.GUID.ToString() + « } »

Mais sans ton code je suis en train de te fournir des documents en vrac sans contexte.

Above all, you have to have the right to modify the registry.

2 Likes

Indeed, if you have the rights to modify the registry then the add-in created with the SW tutorial is displayed without touching anything else

Hello, thank you for your answers.

While starting the code, I received this error: An error occurred while writing the registration information to the registry. Administrator rights are required to use the selected options. Use an administrator command prompt to perform these tasks. Now I open VS in administrator mode but it still doesn't work

Hello

I don't think the problem is the launch of VS in admin mode.
It is mainly the write access to the registry that is the problem (meaning of the error message).
In general, in a secure environment, the registry is locked by IT to prevent anyone from modifying this database, which can completely put a workstation in the lurch, leading to pure and simple formatting.
To deploy the Addin, you have to see with the IT who will take care of the deployment (if they want to do it and if there is no need to do different iterations that will require redeployment).
That's why I personally prefer VBA which is much more flexible with IT and at least I can manage my macros as I see fit.

3 Likes