IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Macros et VBA Excel Discussion :

Excel - enregistrement PDF à la fermeture nommé selon la valeur d'une cellule [XL-2010]


Sujet :

Macros et VBA Excel

  1. #1
    Nouveau Candidat au Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Août 2015
    Messages
    6
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 33
    Localisation : France, Seine et Marne (Île de France)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Août 2015
    Messages : 6
    Points : 0
    Points
    0
    Par défaut Excel - enregistrement PDF à la fermeture nommé selon la valeur d'une cellule
    Bonjour à tous,

    j'ai parcouru plusieurs forums qui traitent du sujet mais je n'ai aucune compétences en VBA et j'obtient toujours des erreurs de compilation, je fait donc appel à vous.

    Je cherche à enregistrer la feuille du classeur nommée "FCL". Il faudrait que l'enregistrement soit executé lors de la fermeture du fichier au format PDF au même emplacement que le fichier excel (sans apercu avant impression) en tenant compte des zones d'impression.
    Nommé selon la valeur de la cellule Q2.

    (sous excel 2010)

    Merci beaucoup pour votre aide !

  2. #2
    Expert éminent sénior
    Avatar de kiki29
    Homme Profil pro
    ex Observeur CGG / Analyste prog.
    Inscrit en
    Juin 2006
    Messages
    6 132
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Finistère (Bretagne)

    Informations professionnelles :
    Activité : ex Observeur CGG / Analyste prog.

    Informations forums :
    Inscription : Juin 2006
    Messages : 6 132
    Points : 11 272
    Points
    11 272
    Par défaut
    Salut, depuis Office 2007 SP2 le format pdf est inclus en natif dans Office, l'usage de l'enregistreur de macros t'apportera un embryon de code naturellement à adapter à ton contexte.

    Bref qqch du genre, à placer dans ThisWorkbook
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    Option Explicit
     
    Private Sub Workbook_BeforeClose(Cancel As Boolean)
    Dim sNomFichier As String, sNom As String
        sNom = Sheets("FCL").Range("Q2")
        If NomFichierValide(sNom) Then
            Sheets("FCL").Select
            sNomFichier = ThisWorkbook.Path & "\" & sNom & ".pdf"
            ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
                                            sNomFichier, Quality:=xlQualityStandard, _
                                            IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
                                            False
        Else
            MsgBox "Fichier PDF non enregistré" & vbCrLf & vbCrLf & "Nom de fichier incorrect", vbInformation + vbOKOnly
        End If
    End Sub
     
    Private Function NomFichierValide(sChaine As String) As Boolean
    Dim i As Long
    Const CaracInterdits As String = """*/:<>?[\]|"
        NomFichierValide = True
        If Len(sChaine) = 0 Then
            NomFichierValide = False
            Exit Function
        End If
        For i = 1 To Len(CaracInterdits)
            If InStr(sChaine, Mid$(CaracInterdits, i, 1)) > 0 Then
                NomFichierValide = False
                Exit Function
            End If
        Next i
    End Function

  3. #3
    Nouveau Candidat au Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Août 2015
    Messages
    6
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 33
    Localisation : France, Seine et Marne (Île de France)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Août 2015
    Messages : 6
    Points : 0
    Points
    0
    Par défaut
    Super merci beaucoup!
    Seulement j'aurais besoin de pouvoir "overwrite" le fichier
    Par exemple j'enregistre un premier pdf (en fermant l'excel) nommé "123"
    puis modifier le fichier excel et lorsque je le ferme qu'il mette à jour le pdf en conservant le même nom.

    Actuellement excel m'indique une erreur : "L'imprimante fonctionne mal..."

    Merci

  4. #4
    Expert éminent sénior
    Avatar de kiki29
    Homme Profil pro
    ex Observeur CGG / Analyste prog.
    Inscrit en
    Juin 2006
    Messages
    6 132
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Finistère (Bretagne)

    Informations professionnelles :
    Activité : ex Observeur CGG / Analyste prog.

    Informations forums :
    Inscription : Juin 2006
    Messages : 6 132
    Points : 11 272
    Points
    11 272
    Par défaut
    Salut, ici sous Excel 2007/W8.1 aucun problème de ce genre, ni message d'erreur saugrenu.

    A tout hasard rajouter dans ThisWorkbook :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    Private Function ExistenceFichier(sFichier As String) As Boolean
        ExistenceFichier = Dir$(sFichier) <> ""
    End Function
    et
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    If ExistenceFichier(sNomFichier) Then Kill sNomFichier
    à l'endroit idoine dans la procédure Workbook_BeforeClose

  5. #5
    Nouveau Candidat au Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Août 2015
    Messages
    6
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 33
    Localisation : France, Seine et Marne (Île de France)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Août 2015
    Messages : 6
    Points : 0
    Points
    0
    Par défaut
    - Lorsque j'enregistre le fichier pour la première fois (par fermeture d'excel) je doit confirmer l'imprimante comme suis :

    Nom : Sans titre.png
Affichages : 432
Taille : 5,1 Ko

    Pourrait-ont intégrer ce paramètre directement dans le code ?

    - J'ai intégré les nouvelles fonction de cette façon :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    Option Explicit
     
    Private Function ExistenceFichier(sFichier As String) As Boolean
        ExistenceFichier = Dir$(sFichier) <> ""
    End Function
    
    Private Sub Workbook_BeforeClose(Cancel As Boolean)
    Dim sNomFichier As String, sNom As String
        sNom = Sheets("FCL").Range("Q2")
        If ExistenceFichier(sNomFichier) Then Kill sNomFichier
        If NomFichierValide(sNom) Then
            Sheets("FCL").Select
            sNomFichier = ThisWorkbook.Path & "\" & sNom & ".pdf"
            ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
                                            sNomFichier, Quality:=xlQualityStandard, _
                                            IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
                                            False
        Else
            MsgBox "Fichier PDF non enregistré" & vbCrLf & vbCrLf & "Nom de fichier incorrect", vbInformation + vbOKOnly
        End If
    End Sub
     
    
    Private Function NomFichierValide(sChaine As String) As Boolean
    Dim i As Long
    Const CaracInterdits As String = """*/:<>?[\]|"
        NomFichierValide = True
        If Len(sChaine) = 0 Then
            NomFichierValide = False
            Exit Function
        End If
        For i = 1 To Len(CaracInterdits)
            If InStr(sChaine, Mid$(CaracInterdits, i, 1)) > 0 Then
                NomFichierValide = False
                Exit Function
            End If
        Next i
    End Function

    J'obtient l'erreur :

    Nom : 8psMbPD.png
Affichages : 330
Taille : 4,8 Ko


    Merci de votre aide

  6. #6
    Expert éminent sénior
    Avatar de kiki29
    Homme Profil pro
    ex Observeur CGG / Analyste prog.
    Inscrit en
    Juin 2006
    Messages
    6 132
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Finistère (Bretagne)

    Informations professionnelles :
    Activité : ex Observeur CGG / Analyste prog.

    Informations forums :
    Inscription : Juin 2006
    Messages : 6 132
    Points : 11 272
    Points
    11 272
    Par défaut
    Salut, depuis Office 2007 SP2 le format pdf est inclus en natif dans Office
    donc les Master PDF Editor et autres sont inutiles sous Office sauf si l'on veut manipuler les fichiers PDF, ici via PDFCreator, Adobe Acrobat Reader et Distiller.

    pour
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    If ExistenceFichier(sNomFichier) Then Kill sNomFichier
    c'est normal qu'il renvoie "fichier introuvable" car collé n'importe où ! relis ton code et réfléchis un peu.

  7. #7
    Nouveau Candidat au Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Août 2015
    Messages
    6
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 33
    Localisation : France, Seine et Marne (Île de France)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Août 2015
    Messages : 6
    Points : 0
    Points
    0
    Par défaut
    J'en suis arrivé à ça

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
     
    Option Explicit
     
    Private Function ExistenceFichier(sFichier As String) As Boolean
        ExistenceFichier = Dir$(sFichier) <> ""
    End Function
     
    Private Sub Workbook_BeforeClose(Cancel As Boolean)
    Dim sNomFichier As String, sNom As String
        sNom = Sheets("FCL").Range("Q2")
        If NomFichierValide(sNom) Then
            Sheets("FCL").Select
            sNomFichier = ThisWorkbook.Path & "\" & sNom & ".pdf"
            ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
                                            sNomFichier, Quality:=xlQualityStandard, _
                                            IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
                                            False
        Else
            If ExistenceFichier(sNomFichier) Then Kill sNomFichier
            MsgBox "Fichier PDF non enregistré" & vbCrLf & vbCrLf & "Nom de fichier incorrect", vbInformation + vbOKOnly
        End If
    End Sub
     
     
    Private Function NomFichierValide(sChaine As String) As Boolean
    Dim i As Long
    Const CaracInterdits As String = """*/:<>?[\]|"
        NomFichierValide = True
        If Len(sChaine) = 0 Then
            NomFichierValide = False
            Exit Function
        End If
        For i = 1 To Len(CaracInterdits)
            If InStr(sChaine, Mid$(CaracInterdits, i, 1)) > 0 Then
                NomFichierValide = False
                Exit Function
            End If
        Next i
    End Function
    Merci beaucoup pour ton aide !

  8. #8
    Expert éminent sénior
    Avatar de kiki29
    Homme Profil pro
    ex Observeur CGG / Analyste prog.
    Inscrit en
    Juin 2006
    Messages
    6 132
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Finistère (Bretagne)

    Informations professionnelles :
    Activité : ex Observeur CGG / Analyste prog.

    Informations forums :
    Inscription : Juin 2006
    Messages : 6 132
    Points : 11 272
    Points
    11 272
    Par défaut
    Salut, je voyais plutôt qqch comme ceci :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    Private Sub Workbook_BeforeClose(Cancel As Boolean)
    Dim sNomFichier As String, sNom As String
        sNom = Sheets("FCL").Range("Q2")
        If NomFichierValide(sNom) Then
            Sheets("FCL").Select
            sNomFichier = ThisWorkbook.Path & "\" & sNom & ".pdf"
            If ExistenceFichier(sNomFichier) Then Kill sNomFichier
            ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
                                            sNomFichier, Quality:=xlQualityStandard, _
                                            IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
                                            False
        Else
            MsgBox "Fichier PDF non enregistré" & vbCrLf & vbCrLf & "Nom de fichier incorrect", vbInformation + vbOKOnly
        End If
    End Sub

  9. #9
    Nouveau Candidat au Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Août 2015
    Messages
    6
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 33
    Localisation : France, Seine et Marne (Île de France)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Août 2015
    Messages : 6
    Points : 0
    Points
    0
    Par défaut
    Ok, merci.

    Du coup si je comprend bien le fait de remonté cette ligne fait que la macro test dès le départ si il y a déjà un pdf et le supprime (si il existe) plutôt que de le créer et tester après ?

    Je cherche à mettre une boite de dialogue Oui Non, elle fonctionne (que je clique sur oui ou non) seulement j'ai une erreur lors du non : "Propriété ou méthode non géré par cet objet"

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    Private Sub Workbook_BeforeClose(Cancel As Boolean)
    Dim sNomFichier As String, sNom As String
        sNom = Sheets("FCL").Range("Q2")
        If MsgBox("Would you create a PDF file ?", vbYesNo, "Create PDF ?") = vbNo Then
            Application.End
        End If
        If NomFichierValide(sNom) Then
            Sheets("FCL").Select
            sNomFichier = ThisWorkbook.Path & "\" & sNom & ".pdf"
            If ExistenceFichier(sNomFichier) Then Kill sNomFichier
            ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
                                            sNomFichier, Quality:=xlQualityStandard, _
                                            IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
                                            False
        Else
            MsgBox "Fichier PDF non enregistré" & vbCrLf & vbCrLf & "Nom de fichier incorrect", vbInformation + vbOKOnly
        End If
    End Sub
    Une piste ?

  10. #10
    Inactif  

    Homme Profil pro
    Développeur .NET
    Inscrit en
    Janvier 2012
    Messages
    4 903
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 68
    Localisation : Canada

    Informations professionnelles :
    Activité : Développeur .NET
    Secteur : Finance

    Informations forums :
    Inscription : Janvier 2012
    Messages : 4 903
    Points : 10 166
    Points
    10 166
    Billets dans le blog
    36
    Par défaut
    Bonjour,

    Regarde l'exemple qu'ils donnent dans l'aide de VBA pour Msgbox. Ce n'est pas dur à trouver; tu cliques sur msgbox dans l'éditeur et tu appuies sur

    Et puis tu pourras faire la même chose pour Application et tu nous diras si l'objet Application a une méthode End

    Et puis tu feras la même chose pour End et tu te demanderas si End vient seul ou au bout de quelque chose.

    Et puis tu devrais réviser ton Anglais.

    "Would you create a PDF file ?" est une expression qui se traduit par "Créeriez-vous un fichier PDF ?" ou "Auriez-vous créé un fichier PDF ?" En anglais, une question qui contient Would vient avec un if et une condition.

    Quand on utilise would autrement que dans une question, would prend le sens de aurais dû.

  11. #11
    Expert éminent sénior
    Avatar de kiki29
    Homme Profil pro
    ex Observeur CGG / Analyste prog.
    Inscrit en
    Juin 2006
    Messages
    6 132
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Finistère (Bretagne)

    Informations professionnelles :
    Activité : ex Observeur CGG / Analyste prog.

    Informations forums :
    Inscription : Juin 2006
    Messages : 6 132
    Points : 11 272
    Points
    11 272
    Par défaut
    Salut, bestialement qqch du genre :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    Private Sub Workbook_BeforeClose(Cancel As Boolean)
    Dim sNomFichier As String, sNom As String, Rep As Long
     
        Rep = MsgBox("Would you create a PDF file ?", vbYesNo + vbDefaultButton1, "Create PDF ?")
        If Rep = 7 Then Exit Sub
     
        sNom = Sheets("FCL").Range("Q2")
     
        If NomFichierValide(sNom) Then
            Sheets("FCL").Select
            sNomFichier = ThisWorkbook.Path & "\" & sNom & ".pdf"
            If ExistenceFichier(sNomFichier) Then Kill sNomFichier
            ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
                                            sNomFichier, Quality:=xlQualityStandard, _
                                            IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
                                            False
        Else
            MsgBox "Fichier PDF non enregistré" & vbCrLf & vbCrLf & "Nom de fichier incorrect", vbInformation + vbOKOnly
        End If
    End Sub
    P.-S: Parlant Anglais comme une vache espagnole, malgré 19 ans de géophysique à l'étranger, je laisse à Clément le soin des corrections linguistiques ...

  12. #12
    Nouveau Candidat au Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Août 2015
    Messages
    6
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 33
    Localisation : France, Seine et Marne (Île de France)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Août 2015
    Messages : 6
    Points : 0
    Points
    0
    Par défaut
    Ok merci.

    Par contre pour la traduction il me semble que le "would" est une forme de politesse, il ne faut pas traduire littéralement un texte. Je me souvenait de "Would you marry me ?" Qui signifie "Veux-tu m'épouser ?".

    Peut-être devrait-je plutôt utiliser "will", mais sinon je pense que la syntaxe est correcte.

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Réponses: 0
    Dernier message: 17/03/2011, 21h42
  2. [XL-2007] calculez ou non selon la valeur d'une cellule
    Par jacomo dans le forum Excel
    Réponses: 2
    Dernier message: 17/01/2011, 00h44
  3. Réponses: 1
    Dernier message: 18/12/2009, 20h43
  4. Réponses: 7
    Dernier message: 24/11/2008, 21h44
  5. Afficher Une Liste Selon La Valeur D'une Cellule
    Par Kevin_18 dans le forum Excel
    Réponses: 10
    Dernier message: 02/07/2007, 19h22

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo