Générer un PDF par Macro VBA sous Excel

Toutes les Solutions affiliées aux PDF (Portable Document Format)

Générer un PDF par Macro VBA sous Excel

Message non lupar hastursoft » Sam 26 Déc 2009 00:20

Image => Image

Vous voulez que votre macro VBA Excel imprime en format PDF votre page encours... Tant mieux! C'est possible simplement...

La solution est ici: Ci-Dessous (Inutile de Cliquer, Lire la suite ...)

Des fichiers DLL sont copiés dans votre répertoire système lors de l'installation de PDFCreator (depuis la version 0.9.3). Il vous suffit donc de référencer celui qui va bien et de faire appel à ses fonctions, pour piloter le programme PDFCreator.

Les principales étapes sont les suivantes:
  1. Référencer le Fichier DLL
  2. Imprimer l'Onglet Courant
  3. Imprimer Tous les Onglets
  4. Un Petit Exemple
  5. Une Autre Solution

Maintenant en détails ce qu'il vous faut faire:
Image
  1. Référencer le Fichier DLL

  2. Accessible dans les Références, il faut juste le sélectionner :
    Code: Tout sélectionner
    Alt+F11 : Outils / Macro / Visual Basic Editor
    Alt+O: Outils
    R: Références...
    <cliquer> pour sélectionner "PDFCreator"
    A partir de ce moment, les fonctions incluses dans le DLL sont disponibles.

    Image
  3. Imprimer l'Onglet Courant

  4. La Fonction Principale est la suivante : ImprimePDF( "Mon_PDF", "C:\Mes_PDF\")
    Code: Tout sélectionner
    Option Explicit
    Private Declare Sub Sleep Lib "kernel32.dll" (ByVal dwMilliseconds As Long)
       Public Sub ImprimePDF(PDFName As String, PDFLocation As String)
          Dim PDFCreator1 As PDFCreator.clsPDFCreator   ' Objet PDF
          Dim DefaultPrinter As String                  ' Imprimante par Défaut (mémorisation)
          Dim c As Long                                 ' compteur Temporisation
          Dim OutputFilename As String                  ' Nom du Fichier Généré
         
          Set PDFCreator1 = New clsPDFCreator
          With PDFCreator1
             .cStart "/NoProcessingAtStartup"
             .cOption("UseAutosave") = 1
             .cOption("UseAutosaveDirectory") = 1
             .cOption("AutosaveDirectory") = PDFLocation    ' Répertoire de stockage du Fichier PDF généré
             Debug.Print PDFName                            ' Remplace par des _ les caractères interdits
             .cOption("AutosaveFilename") = _
                    PDFName & "-" & ActiveSheet.Name        ' Nom de Fichier = <nom du Fichier>-<nom de l'Onglet>
             .cOption("AutosaveFormat") = 0                 ' 0 = PDF
             DefaultPrinter = .cDefaultPrinter              ' Mémorise l'Imprimante pas défaut
             .cDefaultPrinter = "PDFCreator"                ' écrase par PDFCreator
             .cClearCache
          End With
          ActiveSheet.PrintOut Copies:=1, ActivePrinter:="PDFCreator"
          Do Until PDFCreator1.cCountOfPrintjobs = 1        ' Attend la Fin du travail pour quitter
             DoEvents
             Sleep 1000
          Loop
          Sleep 1000
          PDFCreator1.cPrinterStop = False
         
          c = 0                                                    ' Attend la Fin d'Ecriture
          Do While (PDFCreator1.cOutputFilename = "") And (c < 50) ' au besoin 50x200ms (1 sec)
             c = c + 1
             Sleep 200
          Loop
          OutputFilename = PDFCreator1.cOutputFilename             ' Récupère le nom du Fichier Généré
          With PDFCreator1
             .cDefaultPrinter = DefaultPrinter                     ' Réattribue l'Imprimante initiale
             Sleep 200                                             ' Tempo de prise en compte avant fermeture
             .cClose
          End With
          Sleep 2000                                               ' Tempo 2 sec permettant d'assurer la libération de PDFCreator de la Mémoire
          If OutputFilename = "" Then
             MsgBox "Création Fichier pdf." & vbCrLf & vbCrLf & _
                "Une Erreur s'est produite: Délai dépassé!", vbExclamation + vbSystemModal
          End If
       End Sub
    Les 2 Arguments à passer à cette Fonction sont: "PDFName": Le Nom Principal de votre fichier PDF ("Mon_PDF" par exemple, sachant qu'il sera suivi de "-" puis de "<nom_de_votre_onglet") et de "PDFLocation": Le répertoire de stockage (par exemple: "C:\Mes_PDF\").

    Image
  5. Imprimer Tous les Onglets

  6. La Fonction Principale est la suivante : ImprimeTousPDF( "Mon_PDF", "C:\Mes_PDF\")
    Code: Tout sélectionner
    Option Explicit
    Private Declare Sub Sleep Lib "kernel32.dll" (ByVal dwMilliseconds As Long)
       Public Sub ImprimeTousPDF(PDFName As String, PDFLocation As String)
          Dim PDFCreator1 As PDFCreator.clsPDFCreator
          Dim DefaultPrinter As String                  ' Imprimante par Défaut (mémorisation)
          Dim c As Long                                 ' compteur Temporisation
          Dim OutputFilename As String                  ' Nom du Fichier Généré
          Dim i As Integer                              ' compteur d'onglets
         
          Set PDFCreator1 = New clsPDFCreator
          With PDFCreator1
             .cStart "/NoProcessingAtStartup"
             .cOption("UseAutosave") = 1
             .cOption("UseAutosaveDirectory") = 1
             .cOption("AutosaveDirectory") = PDFLocation    ' Répertoire de stockage du Fichier PDF généré
             Debug.Print PDFName                            ' Remplace par des _ les caractères interdits
             .cOption("AutosaveFilename") = PDFName         ' Nom de Fichier = <nom du Fichier>
             .cOption("AutosaveFormat") = 0                 ' 0 = PDF
             DefaultPrinter = .cDefaultPrinter              ' Mémorise l'Imprimante pas défaut
             .cDefaultPrinter = "PDFCreator"                ' écrase par PDFCreator
             .cClearCache
          End With
          For i = 1 To Application.Sheets.Count
             Application.Sheets(i).PrintOut Copies:=1, ActivePrinter:="PDFCreator"
          Next i
          Do Until PDFCreator1.cCountOfPrintjobs = Application.Sheets.Count        ' Attend la Fin du travail pour quitter
             DoEvents
             Sleep 1000
          Loop
          Sleep 1000
          PDFCreator1.cCombineAll
          Sleep 1000
          PDFCreator1.cPrinterStop = False
       
          c = 0                                                    ' Attend la Fin d'Ecriture
          Do While (PDFCreator1.cOutputFilename = "") And (c < 50) ' au besoin 50x200ms (1 sec)
             c = c + 1
             Sleep 200
          Loop
          OutputFilename = PDFCreator1.cOutputFilename             ' Récupère le nom du Fichier Généré
          With PDFCreator1
             .cDefaultPrinter = DefaultPrinter                     ' Réattribue l'Imprimante initiale
             Sleep 200                                             ' Tempo de prise en compte avant fermeture
             .cClose
          End With
          Sleep 2000                                               ' Tempo 2 sec permettant d'assurer la libération de PDFCreator de la Mémoire
          If OutputFilename = "" Then
             MsgBox "Création Fichier pdf." & vbCrLf & vbCrLf & _
                "Une Erreur s'est produite: Délai dépassé!", vbExclamation + vbSystemModal
          End If
       End Sub
    Les 2 Arguments à passer à cette Fonction sont: "PDFName": Le Nom Principal de votre fichier PDF ("Mon_PDF" par exemple) et de "PDFLocation": Le répertoire de stockage (par exemple: "C:\Mes_PDF\").

    Image
  7. Un Petit Exemple

  8. Entrer dans votre Excel Favori, puis dans Visual Basic (Alt+F11) et Importer y le fichier ci-joint : Petit_Test_PDF.bas (clic-droit + enregistrer la cible du lien sous...)
    Il contient les Codes vus en 2. et 3. ainsi qu'un programme Petit_Test() décrit ci-après:
    Code: Tout sélectionner
    Public Sub Petit_Test()   ' Met des données dans les 3 principaux onglets
       Sheets(1).Range("A1").Value = "Petit Test - Ceci est la page 1"
       Sheets(2).Range("A1").Value = "Petit Test - Ceci est la page 2"
       Sheets(3).Range("A1").Value = "Petit Test - Ceci est la page 3"
       
       ' Imprime la page de l'onglet principal
       Call ImprimePDF("Mon_PDF", "C:\")
       
       ' Imprime la page de tous les onglets dans un seul document
       Call ImprimeTousPDF("Mon_PDF", "C:\")
          MsgBox "Petit Test Terminé" & vbCrLf & vbCrLf & _
             "Fichiers PDF générés dans C:\", vbExclamation + vbSystemModal
    Exécuter la Macro nommée "Petit_Test"
    Cela ne marche pas ? N'avez-vous pas oublié l'étape 1. ?
    Cela ne marche toujours pas ? Si vous venez d'installer PDF Creator... un petit redémarrage du PC et le tour est joué (histoire que le DLL soit bien pris en compte dans le référencement).

    Image
  9. Une Autre Solution

  10. Grace à vba_lover1, une nouvelle possibilité existe, plus simple 'encore' à mettre en oeuvre. Suivez cette solution.


A vous les nombreux rapports générés automatiquement sans plus aucun effort...
Dernière édition par hastursoft le Lun 6 Juin 2011 23:32, édité 2 fois.
Raison: lier le nouveau sujet du module mdPDFCreator
hastursoft
Administrateur
Administrateur
 
Messages: 273
Inscription: Sam 14 Juin 2008 21:02

Si Vous avez Trouvé votre Bonheur,
ou si vous voulez aider ce site à progresser...
Merci de penser à
donate
ou bien encore, Inscrivez-Vous ! (c'est gratuit et sans publicité bloquante)
Vous pourrez suivre les évolutions, les mises à jour, et participer... MERCI.

Create a PDF with VBA under Excel Macro

Message non lupar hastursoft » Lun 6 Juin 2011 23:32

Image => Image

You need that your VBA Macro Excel create a PDF file of your active sheet... Well ! It's easy to do ...

The solution is here: See Below (no need to click, just read the following...)

DLL files are installed in your system folder while installing PDFCreator (since the version 0.9.3). You just have to make a reference to the one you need and simply use its functions to manage PDFCreator without user inputs.

The main steps are:
  1. Add a Reference to the DLL File
  2. Print the Active Sheet
  3. Print All the Sheets
  4. A Little Example
  5. Another Way

Now in details what You have to do:
Image
  1. Add a Reference to the DLL File

  2. Reachable in the References, you just have to select it :
    Code: Tout sélectionner
    Alt+F11 : Outils / Macro / Visual Basic Editor
    Alt+O: Outils
    R: References...
    <click> to select "PDFCreator"
    Nota: Short-cuts will be different in UK version of Excel. If you know them, fell free to send me them (PM or email).
    Right Now, all functions included in the DLL are available.

    Image
  3. Print the Active Sheet

  4. The Main Function is : ImprimePDF( "My_PDF", "C:\My_PDFs\")
    Code: Tout sélectionner
    Option Explicit
    Private Declare Sub Sleep Lib "kernel32.dll" (ByVal dwMilliseconds As Long)
       Public Sub ImprimePDF(PDFName As String, PDFLocation As String)
          Dim PDFCreator1 As PDFCreator.clsPDFCreator   ' Objet PDF
          Dim DefaultPrinter As String                  ' Imprimante par Défaut (mémorisation)
          Dim c As Long                                 ' compteur Temporisation
          Dim OutputFilename As String                  ' Nom du Fichier Généré
         
          Set PDFCreator1 = New clsPDFCreator
          With PDFCreator1
             .cStart "/NoProcessingAtStartup"
             .cOption("UseAutosave") = 1
             .cOption("UseAutosaveDirectory") = 1
             .cOption("AutosaveDirectory") = PDFLocation    ' Répertoire de stockage du Fichier PDF généré
             Debug.Print PDFName                            ' Remplace par des _ les caractères interdits
             .cOption("AutosaveFilename") = _
                    PDFName & "-" & ActiveSheet.Name        ' Nom de Fichier = <nom du Fichier>-<nom de l'Onglet>
             .cOption("AutosaveFormat") = 0                 ' 0 = PDF
             DefaultPrinter = .cDefaultPrinter              ' Mémorise l'Imprimante par défaut
             .cDefaultPrinter = "PDFCreator"                ' écrase par PDFCreator
             .cClearCache
          End With
          ActiveSheet.PrintOut Copies:=1, ActivePrinter:="PDFCreator"
          Do Until PDFCreator1.cCountOfPrintjobs = 1        ' Attend la Fin du travail pour quitter
             DoEvents
             Sleep 1000
          Loop
          Sleep 1000
          PDFCreator1.cPrinterStop = False
         
          c = 0                                                    ' Attend la Fin d'Ecriture
          Do While (PDFCreator1.cOutputFilename = "") And (c < 50) ' au besoin 50x200ms (1 sec)
             c = c + 1
             Sleep 200
          Loop
          OutputFilename = PDFCreator1.cOutputFilename             ' Récupère le nom du Fichier Généré
          With PDFCreator1
             .cDefaultPrinter = DefaultPrinter                     ' Réattribue l'Imprimante initiale
             Sleep 200                                             ' Tempo de prise en compte avant fermeture
             .cClose
          End With
          Sleep 2000                                               ' Tempo 2 sec permettant d'assurer la libération de PDFCreator de la Mémoire
          If OutputFilename = "" Then
             MsgBox "Création Fichier pdf." & vbCrLf & vbCrLf & _
                "Une Erreur s'est produite: Délai dépassé!", vbExclamation + vbSystemModal
          End If
       End Sub
    The 2 Arguments to give at this Function are: "PDFName": The Principal Name of your PDF File ("My_PDF" for example, knowing that it will be followed by "-" and by "<name_of_your_sheet>") and "PDFLocation": The Storage Folder (for example: "C:\My_PDFs\").

    Image
  5. Print All the Sheets

  6. The Main Function is : ImprimeTousPDF( "My_PDF", "C:\My_PDFs\")
    Code: Tout sélectionner
    Option Explicit
    Private Declare Sub Sleep Lib "kernel32.dll" (ByVal dwMilliseconds As Long)
       Public Sub ImprimeTousPDF(PDFName As String, PDFLocation As String)
          Dim PDFCreator1 As PDFCreator.clsPDFCreator
          Dim DefaultPrinter As String                  ' Imprimante par Défaut (mémorisation)
          Dim c As Long                                 ' compteur Temporisation
          Dim OutputFilename As String                  ' Nom du Fichier Généré
          Dim i As Integer                              ' compteur d'onglets
         
          Set PDFCreator1 = New clsPDFCreator
          With PDFCreator1
             .cStart "/NoProcessingAtStartup"
             .cOption("UseAutosave") = 1
             .cOption("UseAutosaveDirectory") = 1
             .cOption("AutosaveDirectory") = PDFLocation    ' Répertoire de stockage du Fichier PDF généré
             Debug.Print PDFName                            ' Remplace par des _ les caractères interdits
             .cOption("AutosaveFilename") = PDFName         ' Nom de Fichier = <nom du Fichier>
             .cOption("AutosaveFormat") = 0                 ' 0 = PDF
             DefaultPrinter = .cDefaultPrinter              ' Mémorise l'Imprimante par défaut
             .cDefaultPrinter = "PDFCreator"                ' écrase par PDFCreator
             .cClearCache
          End With
          For i = 1 To Application.Sheets.Count
             Application.Sheets(i).PrintOut Copies:=1, ActivePrinter:="PDFCreator"
          Next i
          Do Until PDFCreator1.cCountOfPrintjobs = Application.Sheets.Count        ' Attend la Fin du travail pour quitter
             DoEvents
             Sleep 1000
          Loop
          Sleep 1000
          PDFCreator1.cCombineAll
          Sleep 1000
          PDFCreator1.cPrinterStop = False
       
          c = 0                                                    ' Attend la Fin d'Ecriture
          Do While (PDFCreator1.cOutputFilename = "") And (c < 50) ' au besoin 50x200ms (1 sec)
             c = c + 1
             Sleep 200
          Loop
          OutputFilename = PDFCreator1.cOutputFilename             ' Récupère le nom du Fichier Généré
          With PDFCreator1
             .cDefaultPrinter = DefaultPrinter                     ' Réattribue l'Imprimante initiale
             Sleep 200                                             ' Tempo de prise en compte avant fermeture
             .cClose
          End With
          Sleep 2000                                               ' Tempo 2 sec permettant d'assurer la libération de PDFCreator de la Mémoire
          If OutputFilename = "" Then
             MsgBox "Création Fichier pdf." & vbCrLf & vbCrLf & _
                "Une Erreur s'est produite: Délai dépassé!", vbExclamation + vbSystemModal
          End If
       End Sub
    The 2 Arguments to give at this Function are: "PDFName": The Principal Name of your PDF File ("My_PDF" for example, knowing that it will be followed by "-" and by "<name_of_your_sheet>") and "PDFLocation": The Storage Folder (for example: "C:\My_PDFs\").

    Image
  7. A Little Example

  8. Enter in your favorite Excel, then in Visual Basic (Alt+F11) and Import this file : Petit_Test_PDF.bas (right-clic + save ...)
    It contains the source codes shown in 2. and 3. and a little program named Petit_Test() describe below:
    Code: Tout sélectionner
    Public Sub Petit_Test()   ' Met des données dans les 3 principaux onglets
       Sheets(1).Range("A1").Value = "Petit Test - Ceci est la page 1"
       Sheets(2).Range("A1").Value = "Petit Test - Ceci est la page 2"
       Sheets(3).Range("A1").Value = "Petit Test - Ceci est la page 3"
       
       ' Imprime la page de l'onglet principal
       Call ImprimePDF("Mon_PDF", "C:\")
       
       ' Imprime la page de tous les onglets dans un seul document
       Call ImprimeTousPDF("Mon_PDF", "C:\")
          MsgBox "Petit Test Terminé" & vbCrLf & vbCrLf & _
             "Fichiers PDF générés dans C:\", vbExclamation + vbSystemModal
    Run the Macro named "Petit_Test"
    It writes datas on sheet 1, 2 and 3. It prints on C:\ a PDF File with only the first page. It prints on C:\ a PDF File with only all pages.

    That doesn't work ? Haven't You forget to do the Step 1. ?
    That's always not work ? If you went to install PDF Creator... a little reboot and it will be good (to let Windows see and install correctly the reference of the DLL).

    Image
  9. Another Way

  10. vba_lover1 gives us another way to print, 'more' simple. Follow this other solution.

For you all the many PDF reports automatically and easily generated ...
Dernière édition par hastursoft le Lun 6 Juin 2011 23:31, édité 3 fois.
Raison: link the other solution with mdPDFCreator


Sujet remonté par hastursoft le Lun 6 Juin 2011 23:32.
hastursoft
Administrateur
Administrateur
 
Messages: 273
Inscription: Sam 14 Juin 2008 21:02


Retourner vers PDF

 


  • Articles en relation
    Réponses
    Vus
    Dernier message

Qui est en ligne

Utilisateurs parcourant ce forum: Aucun utilisateur enregistré et 1 invité

Si Vous avez Trouvé votre Bonheur,
ou si vous voulez aider ce site à progresser...
Merci de penser à
donate
ou bien encore, Inscrivez-Vous ! (c'est gratuit et sans publicité bloquante)
Vous pourrez suivre les évolutions, les mises à jour, et participer... MERCI.