Macro - PDF Drawing - Special Name - Multiple Folders

Hello 
I had already posted a few months ago a request... After multiple unsuccessful attempts, I clarify what I want to put in place to save me a lot of time

As you will surely understand by the simplicity of the macro, I don't know anything about it, I try to learn but it's quite complex... So by the way, if you have a book name or a site to learn, I'm interested. 

The end goal of macro:
I have a plan with one or more sheets
I want to export it as a single PDF file in two folders.

  1. on the desktop
  2. in the folder where the drawing file is saved.

I also want it to be renamed as follows: 
"City - Street/Neighborhood - Ind. (hint letter) - DD.MM.YYYY"
For example, if I take the one from my photo above, it will be: 
"St Malo de Guersac - Allée des garennes - Ind. A - 30.01.2019"Currently I have tried a lot of macro, hacked some without success.
The only one that works but that forces me to rename and copy is this one (see attached file)
 

Thanks in advance to all those who can help me


ext_to_pdf.swp

Hello

You already have all the answers to your old request, see HERE.

Is the goal for us to write this specific macro for you?

For the sites, you can try:

- https://excel-malin.com/tutoriels-vba/

- https://excel.developpez.com/cours/?page=prog#prog

- https://openclassrooms.com/fr/courses/825502-analysez-des-donnees-avec-excel/822888-premiers-pas-en-vba

- http://help.solidworks.com/2019/English/api/HelpViewerDS.aspx?version=2019&prod=api&lang=English&path=SWHelp_List.html&id=e37ca3781e9d493db18b067164ef22f4

- ...

Kind regards

Just like you I don't know much about it, I did my macros by taking bits here and there. Try the attached one, changing the custom properties, and adding a 2nd export with your 2nd path. It works well for me.


file_save_as_dxf.txt
1 Like

Here is what should meet your needs:

Option Explicit

Dim swApp As Object
Dim swModel As SldWorks.ModelDoc2
Dim swCustProp As CustomPropertyManager
Dim valOut1 As String
Dim valOut2 As String
Dim valOut3 As String
Dim resolvedValOut1 As String
Dim resolvedValOut2 As String
Dim resolvedValOut3 As String
Dim Path As String
Dim PathDesktop As String
Dim swModelDocExt As SldWorks.ModelDocExtension
Dim swExportPDFData As SldWorks.ExportPdfData
Dim nFileName As String
Dim nFileName2 As String
Dim boolstatus As Boolean
Dim lErrors As Long
Dim lWarnings As Long
Dim lgFichier As Integer

Sub main()
    Set swApp = Application.SldWorks
    Set swModel = swApp.ActiveDoc

    Dim dateNow As String
    dateNow = Replace(Date, "/", ".")

    If swModel.GetType = swDocDRAWING Then
    
        Path = swModel.GetPathName
        lgFichier = InStrRev(Path, "\", -1, vbTextCompare) - 1
        If lgFichier > 0 Then
              Path = Left(Path, lgFichier)
        End If

        PathDesktop = Environ("USERPROFILE") & "\Desktop"

        Set swCustProp = swModel.Extension.CustomPropertyManager("")
        swCustProp.Get2 "Ville", valOut1, resolvedValOut1
        swCustProp.Get2 "Rue/Quartier", valOut2, resolvedValOut2
        swCustProp.Get2 "Indice", valOut3, resolvedValOut3

        Set swModelDocExt = swModel.Extension
        Set swExportPDFData = swApp.GetExportFileData(1)
        swExportPDFData.ViewPdfAfterSaving = False
        
        nFileName = Path & "\" & resolvedValOut1 & " - " & resolvedValOut2 & " - Ind." & resolvedValOut3 & " - " & dateNow & ".PDF"
        boolstatus = swModelDocExt.SaveAs(nFileName, 0, 0, swExportPDFData, lErrors, lWarnings)
        
        nFileName2 = PathDesktop & "\" & resolvedValOut1 & " - " & resolvedValOut2 & " - Ind." & resolvedValOut3 & " - " & dateNow & ".PDF"
        boolstatus = swModelDocExt.SaveAs(nFileName2, 0, 0, swExportPDFData, lErrors, lWarnings)

    End If
End Sub

 

Don't forget to put the necessary references (Tools / References...):

Kind regards

1 Like

Hello

No, the goal is not for someone to write a VBA for me.

I tried to do several (I was on my 4th different without success)

I am to learn from forum. I learned to make guitars thanks to that and believe me, no one has put a plane in my place... So my request was renewed because I was discouraged from going around in circles without succeeding in anything. 

Thank you for your answers, I'll see what happens by making the changes you told me. 

I'll come back to you to show what comes out of it

Have a nice day

After some research and attempts, here is what I compiled:

Option Explicit

Dim swApp           As SldWorks.SldWorks
Dim swModel         As SldWorks.ModelDoc2
Dim swDraw          As SldWorks.DrawingDoc
Dim Filepath        As String
Dim fileName        As String
Dim Revision        As String
Dim exportData      As SldWorks.ExportPdfData
Dim lErrors         As Long
Dim lWarnings       As Long
Dim confName        As String
Dim revNmb          As String
Dim val             As String
Dim resolved        As Boolean
Dim swview          As SldWorks.View
Dim swRefModel      As ModelDoc2
Dim swRefAssy       As AssemblyDoc
Dim swCustPropMgr   As SldWorks.CustomPropertyManager
Dim ValOut          As String
Dim numéro          As String
Dim description     As String

Sub Main()
    Set swApp = Application.SldWorks
    Set swModel = swApp.ActiveDoc
    If swModel Is Nothing Then
        MsgBox "Tu as pensé à ouvrir ta mise en plan?", vbCritical
        End
    End If
    If swModel.GetType <> swDocDRAWING Then
        MsgBox "Et si tu ouvrais ta mise en plan avant?", vbCritical
        End
    End If
    Set swDraw = swModel
    If swDraw.GetPathName = "" Then
        swDraw.Save
    End If

    If swModel.GetType = swDocDRAWING Then ' Pour savoir si le document est un plan
            Set swDraw = swApp.ActiveDoc
            Set swview = swDraw.GetFirstView 'selectionne le fond de plan
            Set swview = swview.GetNextView  'selectionne la premier vue
            Set swRefModel = swview.ReferencedDocument
            Set swCustPropMgr = swRefModel.Extension.CustomPropertyManager("")

swCustPropMgr.Get4 "Ville", True, ValOut, "Ville", False   'récupère la valeur de la propriété "Ville"
swCustPropMgr.Get5 "Rue/Quartier", True, ValOut, "Rue/Quartier", False 'récupère la valeur de la propriété "Rue/Quartier"
swCustPropMgr.Get2 "indice", True, ValOut, "indice", False   'récupère la valeur de la propriété "indice"

Dim dateNow As String
dateNow = Replace(Date, "/", ".")

Filepath = "D:\Téléchargements\Plan PDF"
Filepath = Filepath + "\"
fileName = ValOut & " " & "-" & " " & ValOut & " " & "-" & " " & "Ind." & " " & ValOut & " " & "-" & " " & dateNow

swDraw.SaveAs (Filepath + fileName + ".PDF")

Exit Sub
End If

End Sub

 

Let me be clear, I only understood a small part  of all this but it's functional except for a part. 

I've looked at several property recovery topics but I don't understand how it works: 

swCustPropMgr.Get4 "Ville", True, ValOut, "Ville", False   'récupère la valeur de la propriété "Ville"
swCustPropMgr.Get5 "Rue/Quartier", True, ValOut, "Rue/Quartier", False 'récupère la valeur de la propriété "Rue/Quartier"
swCustPropMgr.Get2 "indice", True, ValOut, "indice", False   'récupère la valeur de la propriété "indice"

the Get4 or Get5... I don't see how to say: 

The value assigned to "City" is what is in the next box

and then, to be able to transcribe it in the name because for the moment, apart from the date, the names of the properties are not displayed. Here is the result I get: " -  - Ind.  - 04.02.2019.PDF"

Also, to understand a little more, what is the purpose of all the lines below "Option Explicit" of the style: 

Dim swApp           As SldWorks.SldWorks

 

Thanks in advance

Hello

So already for the lines "Dim xxx As yyyyyyy":

Dim : Declaration of the variable

xxx : name chosen for this variable (without spaces)

As : Declaration of the type of the variable

yyyyyyyy: type of the variable

So "Dim swApp As SldWorks.SldWorks" means that we declare a variable named swApp that is of type SldWorks, see HERE. Some explanations on other types of variables here.

For the Get, Get2, Get3, Get4 and Get5 functions: The Get5 function is an evolution of the Get4 function which is an evolution of the Get3 function which is an evolution of the Get2 function which is an evolution of the Get function, see HERE. Each function has a certain number of arguments that are of a certain type, the order and quantity of these must be respected, some arguments are used to send a value to the function and others are used to retrieve values, which is the case for the Get function, for example:

swCustProp.Get2 "City", valOut1, resolvedValOut1 means that I can retrieve the "Value/Text Expression" in the return variable "valOut1" and the "Evaluated Value" in the return variable "resolvedValOut1" for the custom property named "City".

In your macro there are indeed some problems on the Get functions, already to see if you want to use the most recent one (Get5) or another but choose one and only one then respect the number and type of arguments of the one you will have chosen and finally, the values returned must be in different variables otherwise this one is overwritten as you go along (your ValOut variable). Look at what I did in my macro:

swCustProp.Get2 "City", valOut1, resolvedValOut1
swCustProp.Get2 "Street/Neighborhood", valOut2, resolvedValOut2
swCustProp.Get2 "Index", valOut3, resolvedValOut3

....

nFileName = Path & "\" & resolvedValOut1 & " - " & resolvedValOut2 & " - Ind." & resolvedValOut3 & " - " & dateNow & ".PDF"

There you have it, hoping I've been pretty clear.

Kind regards

 

2 Likes

Hello

Thank you for these explanations. 

I'm going to look at the links you gave me. 

After modification I find myself with a problem I had before, it doesn't recognize the valOut... I don't understand why. Do you have any idea why?

Thanks in advance


save_pdf_test1_04.02.2019.swp

Hello

The macro starts with the "Option Explicit" line, which means that you have to declare the variables explicitly but you are missing the following variables in the declaration lines:

Dim valOut1 As String
Dim valOut2 As String
Dim valOut3 As String
Dim resolvedValOut1 As String
Dim resolvedValOut2 As String
Dim resolvedValOut3 As String

You also need to change "swCustProp" to "swCustPropMgr" in the lines:

swCustProp.Get2 'City', valOut1, resolvedValOut1          ' retrieves the value of the "City" property
swCustProp.Get2 'Street/Neighborhood', valOut2, resolvedValOut2   ' retrieves the value of the "Street/Neighborhood" property
swCustProp.Get2 "Index", valOut3, resolvedValOut3         ' retrieves the value of the "Index" property

since the variable you declared is called "swCustPropMgr".

And finally, you need to clean up the construction of the name of the pdf file in the lines:

Filepath = "D:\Downloads\PDF Plan"
Filepath = Filepath + "\"
nfileName = Path & "\" & resolvedValOut1 & " - " & resolvedValOut2 & " - Ind." & resolvedValOut3 & " - " & dateNow & ".PDF"

swDraw.SaveAs (Filepath + fileName + ".PDF")

This could be as follows:

Filepath = "D:\Downloads\PDF Plan\"

fileName = resolvedValOut1 & " - " & resolvedValOut2 & " - Ind." & resolvedValOut3 & " - " & dateNow & ".PDF"

swDraw.SaveAs (Filepath + fileName )

Be careful to declare the variables and then to use them by their names:

Dim fileName As String

cannot be used as "nfileName"

Kind regards

2 Likes

Re

Can you test it to see if it works with your PC?

I've changed:

  1. the place of registration in order to exclude any problem of conflict or authorization.
  2. Dim dateNow As String, I put it in Option Explicit
  3. swCustProp.Get2 to swCustPropMgr.Get2
  4. the line with Filepath = "C:\" to add the "\" and therefore deleted the next line which becomes useless
  5. nfileName I didn't understand why the "n" before this command line... What is the difference between with and without?

No more error message but I'm going back to the previous problem which gives me a file " -  - Ind. - 05.02.2019"

Could the capitalizations be a problem because I saw a difference (and I can't change it, it corrects it automatically) between ValOut - valOut1 - resolvedValOut1

Kind regards

Option Explicit

Dim swApp               As SldWorks.SldWorks
Dim swModel             As SldWorks.ModelDoc2
Dim swDraw              As SldWorks.DrawingDoc
Dim Filepath            As String
Dim fileName            As String
Dim Revision            As String
Dim exportData          As SldWorks.ExportPdfData
Dim lErrors             As Long
Dim lWarnings           As Long
Dim confName            As String
Dim revNmb              As String
Dim val                 As String
Dim resolved            As Boolean
Dim swview              As SldWorks.View
Dim swRefModel          As ModelDoc2
Dim swRefAssy           As AssemblyDoc
Dim swCustPropMgr       As SldWorks.CustomPropertyManager
Dim dateNow             As String
Dim ValOut              As String
Dim numéro              As String
Dim description         As String
Dim valOut1             As String
Dim valOut2             As String
Dim valOut3             As String
Dim resolvedValOut1     As String
Dim resolvedValOut2     As String
Dim resolvedValOut3     As String

Sub Main()
    Set swApp = Application.SldWorks
    Set swModel = swApp.ActiveDoc
    If swModel Is Nothing Then
        MsgBox "Tu as pensé à ouvrir ta mise en plan?", vbCritical
        End
    End If
    If swModel.GetType <> swDocDRAWING Then
        MsgBox "Et si tu ouvrais ta mise en plan avant?", vbCritical
        End
    End If
    Set swDraw = swModel
    If swDraw.GetPathName = "" Then
        swDraw.Save
    End If

    If swModel.GetType = swDocDRAWING Then                      'Pour savoir si le document est un plan
            Set swDraw = swApp.ActiveDoc                        'selectionne le document actif
            Set swview = swDraw.GetFirstView                    'selectionne le fond de plan
            Set swview = swview.GetNextView                     'selectionne la premier vue
            Set swRefModel = swview.ReferencedDocument
            Set swCustPropMgr = swRefModel.Extension.CustomPropertyManager("")

swCustPropMgr.Get2 "Ville", valOut1, resolvedValOut1           'récupère la valeur de la propriété "Ville"
swCustPropMgr.Get2 "Rue/Quartier", valOut2, resolvedValOut2    'récupère la valeur de la propriété "Rue/Quartier"
swCustPropMgr.Get2 "Indice", valOut3, resolvedValOut3          'récupère la valeur de la propriété "indice"

dateNow = Replace(Date, "/", ".")

Filepath = "C:\"                                                'Destination d'enregistrement du PDF
fileName = resolvedValOut1 & " - " & resolvedValOut2 & " - Ind." & resolvedValOut3 & " - " & dateNow & ".PDF"   'Nom du PDF

swDraw.SaveAs (Filepath + fileName)

Exit Sub
End If

End Sub

 


save_pdf_test1_04.02.2019.swp

Yes, it works as long as the custom properties are created in the custom tab of the room, since that's where you'll get the values through the line "Set swCustPropMgr = swRefModel.Extension.CustomPropertyManager("")".

I get a PDF file named "My City - My Street - Ind.B - 05.02.2019.PDF".

Kind regards

1 Like

I don't understand why, but I have the values that go well in the custom tab...


plcion_-_test.slddrw

Yes, but from your plan, whereas with the lines:

Set swRefModel = swview. ReferencedDocument
Set swCustPropMgr = swRefModel.Extension.CustomPropertyManager("")

You will look for the properties of the Customize tab of the reference part in your drawing view.

Remove your line "Set swRefModel = swview. ReferencedDocument" and replace "swRefModel" with "swModel" in your line "Set swCustPropMgr = swRefModel.Extension.CustomPropertyManager("")" if you want the properties of the drawing.

Kind regards

2 Likes

Thank you d.roger for this help. 

Everything works perfectly. 

Here's the final macro if someone ever needs it. 

Have a good day to you

Option Explicit

Dim swApp               As SldWorks.SldWorks
Dim swModel             As SldWorks.ModelDoc2
Dim swDraw              As SldWorks.DrawingDoc
Dim Filepath            As String
Dim fileName            As String
Dim Revision            As String
Dim exportData          As SldWorks.ExportPdfData
Dim lErrors             As Long
Dim lWarnings           As Long
Dim confName            As String
Dim revNmb              As String
Dim val                 As String
Dim resolved            As Boolean
Dim swview              As SldWorks.View
Dim swRefModel          As ModelDoc2
Dim swRefAssy           As AssemblyDoc
Dim swCustPropMgr       As SldWorks.CustomPropertyManager
Dim dateNow             As String
Dim ValOut              As String
Dim numéro              As String
Dim description         As String
Dim valOut1             As String
Dim valOut2             As String
Dim valOut3             As String
Dim resolvedValOut1     As String
Dim resolvedValOut2     As String
Dim resolvedValOut3     As String

Sub Main()
    
    Set swApp = Application.SldWorks
    Set swModel = swApp.ActiveDoc
    If swModel Is Nothing Then
        MsgBox "Tu as pensé à ouvrir ta mise en plan?", vbCritical
        End
    End If
    
    If swModel.GetType <> swDocDRAWING Then
        MsgBox "Et si tu ouvrais ta mise en plan avant?", vbCritical
        End
    End If
    
    Set swDraw = swModel
    If swDraw.GetPathName = "" Then
        swDraw.Save
    End If

    If swModel.GetType = swDocDRAWING Then                          'Pour savoir si le document est un plan
            Set swDraw = swApp.ActiveDoc                            'selectionne le document actif
            Set swview = swDraw.GetFirstView                        'selectionne le fond de plan
            Set swview = swview.GetNextView                         'selectionne la premier vue
            Set swCustPropMgr = swModel.Extension.CustomPropertyManager("")
    
    swCustPropMgr.Get2 "Ville", valOut1, resolvedValOut1            'récupère la valeur de la propriété "Ville"
    swCustPropMgr.Get2 "Rue/Quartier", valOut2, resolvedValOut2     'récupère la valeur de la propriété "Rue/Quartier"
    swCustPropMgr.Get2 "Indice", valOut3, resolvedValOut3           'récupère la valeur de la propriété "indice"
            
            dateNow = Replace(Date, "/", ".")                       'remplace les / par des . dans la date
    
    Filepath = "D:\Téléchargements\Plan PDF\"                       'Destination d'enregistrement du PDF
    fileName = resolvedValOut1 & " - " & resolvedValOut2 & " - Ind." & resolvedValOut3 & " - " & dateNow & ".PDF"   'Nom du PDF
        
        swDraw.SaveAs (Filepath + fileName)                         'Sauvegarde dans le dossier choisi avec le nom défini par les propriétées

    Exit Sub
    End If

    End Sub

 


save_pdf_-_05.02.2019.swp

You're welcome...

Here is a version with the addition of the double backup as initially requested and the removal of superfluous lines:

Option Explicit

' On définit les variables nécessaires
Dim swApp As Object
Dim swModel As SldWorks.ModelDoc2
Dim swCustProp As CustomPropertyManager
Dim valOut1 As String
Dim valOut2 As String
Dim valOut3 As String
Dim resolvedValOut1 As String
Dim resolvedValOut2 As String
Dim resolvedValOut3 As String
Dim Path As String
Dim PathDesktop As String
Dim swModelDocExt As SldWorks.ModelDocExtension
Dim swExportPDFData As SldWorks.ExportPdfData
Dim nFileName As String
Dim nFileName2 As String
Dim boolstatus As Boolean
Dim lErrors As Long
Dim lWarnings As Long
Dim lgFichier As Integer

Sub main()
' On se raccroche à Solidworks
Set swApp = Application.SldWorks

' On récupère le document actif dans Solidworks
Set swModel = swApp.ActiveDoc

' On vérifie qu'un document est bien ouvert dans Solidworks
If swModel Is Nothing Then
	MsgBox "Un document doit être actif dans Solidworks.", vbCritical
	End
End If

' On vérifie que le document ouvert dans Solidworks est un plan
If swModel.GetType <> swDocDRAWING Then
	MsgBox "Le document actif dans Solidworks doit être un plan.", vbCritical
	End
End If

' On vérifie que le plan ouvert dans Solidworks est bien enregistré
If swModel.GetPathName = "" Then
	swModel.Save
End If

' On récupère la date du jour et on la met dans un format pouvant se mettre dans le nom d'un fichier
Dim dateNow As String
dateNow = Replace(Date, "/", ".")

' On récupère le chemin du dossier d'enregistrement du plan
Path = swModel.GetPathName
lgFichier = InStrRev(Path, "\", -1, vbTextCompare) - 1
If lgFichier > 0 Then
	Path = Left(Path, lgFichier)
End If

' On récupère le chemin du bureau Windows
PathDesktop = Environ("USERPROFILE") & "\Desktop"

' On récupère les valeurs qui nous intéresse dans les propriétés personnalisées du plan
Set swCustProp = swModel.Extension.CustomPropertyManager("")
swCustProp.Get2 "Ville", valOut1, resolvedValOut1
swCustProp.Get2 "Rue/Quartier", valOut2, resolvedValOut2
swCustProp.Get2 "Indice", valOut3, resolvedValOut3

' On définit les paramètres d'export en PDF
Set swModelDocExt = swModel.Extension
Set swExportPDFData = swApp.GetExportFileData(1)
swExportPDFData.ViewPdfAfterSaving = False

' On définit le chemin et le nom du premier fichier pdf à créer
nFileName = Path & "\" & resolvedValOut1 & " - " & resolvedValOut2 & " - Ind." & resolvedValOut3 & " - " & dateNow & ".PDF"

' On sauvegarde le premier fichier pdf
boolstatus = swModelDocExt.SaveAs(nFileName, 0, 0, swExportPDFData, lErrors, lWarnings)

' On définit le chemin et le nom du deuxième fichier pdf à créer
nFileName2 = PathDesktop & "\" & resolvedValOut1 & " - " & resolvedValOut2 & " - Ind." & resolvedValOut3 & " - " & dateNow & ".PDF"

' On sauvegarde le deuxième fichier pdf
boolstatus = swModelDocExt.SaveAs(nFileName2, 0, 0, swExportPDFData, lErrors, lWarnings)

End Sub

 

Kind regards

2 Likes

Hello

Thank you for this macro, it helps me a lot.

On the other hand, in my case, the hint is in the "configuration specific" tab and not in "customize", so when saving it won't look for the hint

I think the problem comes from swParentModel.Extension.CustomPropertyManager("") but I'm not an expert in the discipline at all.

Attached is my program (well copy and paste of several macros)

Thanks in advance


sauv_pdf_ind.swp

Hello

When it's like that, it would be good to create a new discussion and put a link to the original discussion rather than reopening a 1-year-old discussion...

For your case you just have to put the name of the targeted configuration in the quotation marks of your line:

Set swCustPropMgr = swParentModel.Extension.CustomPropertyManager("")

For example:

Set swCustPropMgr = swParentModel.Extension.CustomPropertyManager("Default")

Kind regards