MACRO Création sous-dossiers d'un dossier existant

Bonjour,

j’aurais besoin de vos lumières. Je cherche à faire une macro qui créerait 3 sous-dossiers d’un dossier existant.
Le dossier existant s’appelle BASE et les 3 sous-dossiers s’appellent Option1/Option2/Option3.
J’ai bricolé ce code, mais la macro ne parvient pas à trouver le dossier BASE, donc pas de création de sous-dossiers …

Auriez vous des solutions s’il vous plait ? :smiling_face_with_tear:

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

Sub main()
    ' Initialisation appli SolidWorks
    Set swApp = Application.SldWorks
    Set Part = swApp.ActiveDoc
    
    ' Vérification doc assemblage
    If Part.GetType <> swDocASSEMBLY Then
        MsgBox "Le document actif n'est pas un assemblage. Veuillez lancer la macro sur un assemblage."
        Exit Sub
    End If
    
    ' Vérification existance dossier "BASE"
    Dim plotFolder As Object
    On Error Resume Next
    Set plotFolder = Part.FeatureManager.FeatureByName("BASE")
    On Error GoTo 0

    If plotFolder Is Nothing Then
        MsgBox "Le dossier "BASE" n'existe pas. Créer ce dossier avant d'exécuter la macro."
        Exit Sub
    End If
    
    ' Sélectionner le dossier "BASE" pour y insérer les sous-dossiers
    boolstatus = Part.Extension.SelectByID2("BASE", "FEATURE", 0, 0, 0, False, 0, Nothing, 0)
    
    ' Création sous-dossier "Option1"
    Dim myFeature As Object
    Set myFeature = Part.FeatureManager.InsertFeatureTreeFolder2(swFeatureTreeFolderType_e.swFeatureTreeFolder_EmptyBefore)
    boolstatus = Part.SelectedFeatureProperties(0, 0, 0, 0, 0, 0, 0, 1, 0, "Option1")
    
    ' Création sous-dossier "Option2"
    Set myFeature = Part.FeatureManager.InsertFeatureTreeFolder2(swFeatureTreeFolderType_e.swFeatureTreeFolder_EmptyBefore)
    boolstatus = Part.SelectedFeatureProperties(0, 0, 0, 0, 0, 0, 0, 1, 0, "Option2")
    
    ' Création sous-dossier "Option3"
    Set myFeature = Part.FeatureManager.InsertFeatureTreeFolder2(swFeatureTreeFolderType_e.swFeatureTreeFolder_EmptyBefore)
    boolstatus = Part.SelectedFeatureProperties(0, 0, 0, 0, 0, 0, 0, 1, 0, "Option3")
    
    ' Tout désélectionner
    Part.ClearSelection2 True
    
    MsgBox "Les 3 sous-dossiers ont été créés avec succès dans le dossier "BASE"."
End Sub

Bonjour @MLG ,

FeatureByName est une méthode d’un document de pièce ou d’assemblage, pas de l’objet FeatureManager…

D’autre part, la création d’un dossier ne fonctionne que si un composant est sélectionné dans l’arbre. Pour créer des sous dossiers du dossier « BASE », il faut donc que celui-ci contienne au moins un composant.
Si c’est le cas, les sous-dossiers sont créés.
La macro jointe devrait fonctionner.

CreationSsDossiers.swp (43 Ko)

3 « J'aime »

Les dossiers vides peuvent également être créés, puis déplacés vers le dossier BASE.

Voici la version modifiée/mise à jour de la macro partagée par @m_blt où les sous-dossiers sont ajoutés au dossier BASE vide.

CreationSsDossiersV1.swp (40 KB)

1 « J'aime »

Merci @Deepak_Gupta pour le complément de réponse.
Et très heureux d’accueillir sur ce forum, l’un des grands contributeurs sw d’un autre forum bien connu! :smiley:

2 « J'aime »

Merci @sbadenis :smiling_face_with_three_hearts:

1 « J'aime »

Un GRAND MERCI à @m_blt & @Deepak_Gupta pour leur précieuse aide :+1:

J’ai adapté vos codes et ajouté la création du dossier PLOTS (remplaçant de BASE à l’origine) s’il n’est pas existant. J’ai ajouté aussi la création de configurations dérivées à la config +SOL+PLOTS (et création si celle ci inexistante).

Voici mon code :

'----------------------------------------------------------------------
'MACRO CREATION DOSSIER/SOUS DOSSIERS PLOTS + CREATION CONFIG/SOUS CONFIGS PLOTS
'----------------------------------------------------------------------

Option Explicit

Sub Main()
    Dim swApp           As SldWorks.SldWorks
    Dim swAssemb        As AssemblyDoc
    Dim swFeature       As Feature
    Dim boolstatus      As Boolean
    Dim swPlotFolder    As FeatureFolder
    Dim myFeature       As Feature
    Dim swModel         As SldWorks.ModelDoc2
    Dim swConfMgr       As SldWorks.ConfigurationManager
    Dim swConf          As SldWorks.Configuration
    Dim swDerivConf     As SldWorks.Configuration
'----------------------------------------------------------------------
    Set swApp = Application.SldWorks
    Set swAssemb = swApp.ActiveDoc

    ' Vérif doc assemblage
    If swAssemb.GetType <> swDocASSEMBLY Then
        MsgBox "Le document actif n'est pas un assemblage. Veuillez lancer la macro sur un assemblage."
        Exit Sub
    End If

    ' Vérif existance dossier 'PLOTS'
    Set swFeature = swAssemb.FeatureByName("PLOTS")

    If swFeature Is Nothing Then
        ' Création dossier 'PLOTS' s'il n'existe pas
        boolstatus = swAssemb.Extension.SelectByID2("", "FEATUREMANAGER", 0, 0, 0, False, 0, Nothing, 0)
        Set swFeature = swAssemb.FeatureManager.InsertFeatureTreeFolder2(swFeatureTreeFolderType_e.swFeatureTreeFolder_EmptyBefore)
        swFeature.Name = "PLOTS"
        MsgBox "Le dossier 'PLOTS' a été créé.", vbInformation, "Résultat"
    End If

    ' Une fois le dossier 'PLOTS' trouvé ou créé, ajouter les sous-dossiers
    boolstatus = swAssemb.Extension.SelectByID2("PLOTS", "FTRFOLDER", 0, 0, 0, False, 0, Nothing, 0)
    
    ' Sous-dossier "PLOTS LONGS"
    Set myFeature = swAssemb.FeatureManager.InsertFeatureTreeFolder2(swFeatureTreeFolderType_e.swFeatureTreeFolder_EmptyBefore)
    myFeature.Name = "PLOTS LONGS"
    boolstatus = swAssemb.Extension.ReorderFeature("PLOTS LONGS", swFeature.Name, swMoveLocation_e.swMoveToFolder)
    
    ' Sous-dossier "PLOTS COURTS"
    Set myFeature = swAssemb.FeatureManager.InsertFeatureTreeFolder2(swFeatureTreeFolderType_e.swFeatureTreeFolder_EmptyBefore)
    myFeature.Name = "PLOTS COURTS"
    boolstatus = swAssemb.Extension.ReorderFeature("PLOTS COURTS", swFeature.Name, swMoveLocation_e.swMoveToFolder)
    
    ' Sous-dossier "PLOTS MISE EN PLAN"
    Set myFeature = swAssemb.FeatureManager.InsertFeatureTreeFolder2(swFeatureTreeFolderType_e.swFeatureTreeFolder_EmptyBefore)
    myFeature.Name = "PLOTS MISE EN PLAN"
    boolstatus = swAssemb.Extension.ReorderFeature("PLOTS MISE EN PLAN", swFeature.Name, swMoveLocation_e.swMoveToFolder)
    
    ' Mise à jour FeatureManager
    swAssemb.FeatureManager.UpdateFeatureTree

'----------------------------------------------------------------------

    'Traitement de configurations

    Set swModel = swApp.ActiveDoc

    Set swConfMgr = swModel.ConfigurationManager
    
    ' Vérifier si la configuration cible existe
    Set swConf = swModel.GetConfigurationByName("+SOL+PLOTS")
    If swConf Is Nothing Then
        ' Créer la configuration +SOL+PLOTS si elle n'existe pas
        Set swConf = swConfMgr.AddConfiguration("+SOL+PLOTS", "Configuration principale pour les PLOTS", "", 0, "", "")
        If swConf Is Nothing Then
            MsgBox "Impossible de créer la configuration '+SOL+PLOTS'.", vbCritical
            Exit Sub
        Else
            MsgBox "La configuration '+SOL+PLOTS' a été créée avec succès.", vbInformation
        End If
    End If
    
    ' Vérifier si la configuration dérivée existe déjà
    Set swDerivConf = swModel.GetConfigurationByName("PLOTS COURTS")
    If Not swDerivConf Is Nothing Then
        MsgBox "La configuration dérivée 'PLOTS COURTS' existe déjà.", vbInformation
        Exit Sub
    End If
    
    ' Créer les configurations dérivées
    Set swDerivConf = swConfMgr.AddConfiguration("PLOTS COURTS", "Configuration dérivée de +SOL+PLOTS", "", 1, swConf.Name, "")
    Set swDerivConf = swConfMgr.AddConfiguration("PLOTS LONGS", "Configuration dérivée de +SOL+PLOTS", "", 1, swConf.Name, "")

    
    ' Vérifier si la configuration a été créée
    If swDerivConf Is Nothing Then
        MsgBox "Échec de la création de la configuration dérivée.", vbCritical
    Else
        MsgBox "Configurations dérivées 'PLOTS COURTS' et 'PLOTS LONGS' créées avec succès.", vbInformation
    End If
    
    ''' Activation de la config +SOL+PLOTS
    boolstatus = swModel.ShowConfiguration2("+SOL+PLOTS")

    MsgBox "DOSSIER + SOUS-DOSSIERS PLOTS A JOUR  -  CONFIG + SOUS-CONFIG PLOTS A JOUR.", vbInformation, "Résultat"

End Sub

La MACRO a bien fonctionné dans le cas d’un assemblage avec 3 pièces TEST :

Mais en faisant des test sur d’autres assemblages, j’ai un plantage MACRO dès le début :

image

Je ne comprends pas pourquoi il me dit qu’une variable n’est pas définie alors qu’au premier test cela fonctionnait.

Et au débogage il m’indique cette ligne :

Auriez vous un idée de pourquoi cela fonctionne avec certaines pièces et pas d’autres ?

Il s’agit d’une erreur correcte car il n’y a rien de sélectionné pour ajouter le dossier vide auparavant. Et comme aucun dossier n’est ajouté, la fonctionnalité (dossier) ne peut pas être renommée.

Ainsi, dans un fichier vide, vous pouvez sélectionner les Compagnons (dernière fonctionnalité) et ajouter le dossier avant celui-ci (quelque chose comme les codes ci-dessous)

If swFeature Is Nothing Then
    
        Dim featCount As Long
        featCount = swAssemb.GetFeatureCount
        
        Dim swLastFeat As SldWorks.Feature
        Set swLastFeat = swAssemb.FeatureByPositionReverse(0)
        swLastFeat.Select2 False, -1

        ' Création dossier 'PLOTS' s'il n'existe pas
        'boolstatus = swAssemb.Extension.SelectByID2(swLastFeat.Name, "FEATUREMANAGER", 0, 0, 0, False, 0, Nothing, 0)

        Set swFeature = swAssemb.FeatureManager.InsertFeatureTreeFolder2(swFeatureTreeFolderType_e.swFeatureTreeFolder_EmptyBefore)
        swFeature.Name = "PLOTS"
        MsgBox "Le dossier 'PLOTS' a été créé.", vbInformation, "Résultat"
    End If
4 « J'aime »