Accéder au contenu principal

Kutools for Office — Une Suite. Cinq Outils. Accomplissez Plus.

Comment convertir ou enregistrer un email et ses pièces jointes dans un seul fichier PDF dans Outlook ?

Author Siluvia Last modified

Cet article explique comment enregistrer un message électronique et toutes les pièces jointes qu'il contient dans un seul fichier PDF dans Outlook.

Convertir ou enregistrer un email et ses pièces jointes dans un seul fichier PDF avec un code VBA


Convertir ou enregistrer un email et ses pièces jointes dans un seul fichier PDF avec un code VBA

Veuillez suivre les étapes ci-dessous pour enregistrer un email avec toutes ses pièces jointes dans un seul fichier PDF dans Outlook.

1. Sélectionnez un email avec des pièces jointes que vous souhaitez enregistrer dans un seul fichier PDF, puis appuyez sur les touches Alt + F11 pour ouvrir la fenêtre Microsoft Visual Basic for Applications.

2. Dans la fenêtre Microsoft Visual Basic for Applications, cliquez sur Insérer > Module. Ensuite, copiez le code VBA ci-dessous dans la fenêtre Module.

Code VBA : Enregistrer un email et une pièce jointe dans un seul fichier PDF

Public Sub MergeMailAndAttachsToPDF()
'Update by Extendoffice 2018/3/5
Dim xSelMails As MailItem
Dim xFSysObj As FileSystemObject
Dim xOverwriteBln As Boolean
Dim xLooper As Integer
Dim xEntryID As String
Dim xNameSpace As Outlook.NameSpace
Dim xMail As Outlook.MailItem
Dim xExt As String
Dim xSendEmailAddr, xCompanyDomain As String
Dim xWdApp As Word.Application
Dim xDoc, xNewDoc As Word.Document
Dim I As Integer
Dim xPDFSavePath As String
Dim xPath As String
Dim xFileArr() As String
Dim xExcel As Excel.Application
Dim xWb As Workbook
Dim xWs As Worksheet
Dim xTempDoc As Word.Document

On Error Resume Next
If (Outlook.ActiveExplorer.Selection.Count > 1) Or (Outlook.ActiveExplorer.Selection.Count = 0) Then
    MsgBox "Please Select a email.", vbInformation + vbOKOnly
    Exit Sub
End If
Set xSelMails = Outlook.ActiveExplorer.Selection.Item(1)
xEntryID = xSelMails.EntryID
Set xNameSpace = Application.GetNamespace("MAPI")
Set xMail = xNameSpace.GetItemFromID(xEntryID)

xSendEmailAddr = xMail.SenderEmailAddress
xCompanyDomain = Right(xSendEmailAddr, Len(xSendEmailAddr) - InStr(xSendEmailAddr, "@"))
xOverwriteBln = False
Set xExcel = New Excel.Application
xExcel.Visible = False
Set xWdApp = New Word.Application
xExcel.DisplayAlerts = False
xPDFSavePath = xExcel.Application.GetSaveAsFilename(InitialFileName:="", FileFilter:="PDF Files(*.pdf),*.pdf")
If xPDFSavePath = "False" Then
    xExcel.DisplayAlerts = True
    xExcel.Quit
    xWdApp.Quit
    Exit Sub
End If
xPath = Left(xPDFSavePath, InStrRev(xPDFSavePath, "\"))
cPath = xPath & xCompanyDomain & "\"
yPath = cPath & Format(Now(), "yyyy") & "\"
mPath = yPath & Format(Now(), "MMMM") & "\"
If Dir(xPath, vbDirectory) = vbNullString Then
   MkDir xPath
End If
EmailSubject = CleanFileName(xMail.Subject)
xSaveName = Format(xMail.ReceivedTime, "yyyymmdd") & "_" & EmailSubject & ".doc"
Set xFSysObj = CreateObject("Scripting.FileSystemObject")
If xOverwriteBln = False Then
   xLooper = 0
  Do While xFSysObj.FileExists(yPath & xSaveName)
      xLooper = xLooper + 1
      xSaveName = Format(xMail.ReceivedTime, "yyyymmdd") & "_" & EmailSubject & "_" & xLooper & ".doc"
   Loop
Else
   If xFSysObj.FileExists(yPath & xSaveName) Then
      xFSysObj.DeleteFile yPath & xSaveName
   End If
End If
xMail.SaveAs xPath & xSaveName, olDoc
If xMail.Attachments.Count > 0 Then
   For Each atmt In xMail.Attachments
      xExt = SplitPath(atmt.filename, 2)
      If (xExt = ".docx") Or (xExt = ".doc") Or (xExt = ".docm") Or (xExt = ".dot") Or (xExt = ".dotm") Or (xExt = ".dotx") _
      Or (xExt = ".xlsx") Or (xExt = ".xls") Or (xExt = ".xlsm") Or (xExt = ".xlt") Or (xExt = ".xltm") Or (xExt = ".xltx") Then
        atmtName = CleanFileName(atmt.filename)
        atmtSave = xPath & Format(xMail.ReceivedTime, "yyyymmdd") & "_" & atmtName
        atmt.SaveAsFile atmtSave
      End If
   Next
End If
Set xNewDoc = xWdApp.Documents.Add("Normal", False, wdNewBlankDocument, False)
Set xFilesFld = xFSysObj.GetFolder(xPath)
xFileArr() = GetFiles(xPath)
For I = 0 To UBound(xFileArr()) - 1
    xExt = SplitPath(xFileArr(I), 2)
    If (xExt = ".xlsx") Or (xExt = ".xls") Or (xExt = ".xlsm") Or (xExt = ".xlt") Or _
       (xExt = ".xltm") Or (xExt = ".xltx") Then  'conver excel to word
        Set xWb = xExcel.Workbooks.Open(xPath & xFileArr(I))
        Set xTempDoc = xWdApp.Documents.Add("Normal", False, wdNewBlankDocument, False)
        Set xWs = xWb.ActiveSheet
        xWs.UsedRange.Copy
        xTempDoc.Content.PasteAndFormat wdFormatOriginalFormatting
        xTempDoc.SaveAs2 xPath & xWs.Name + ".docx", wdFormatXMLDocument
        xWb.Close False
        Kill xPath & xFileArr(I)
        xTempDoc.Close wdDoNotSaveChanges, wdOriginalDocumentFormat, False
    End If
Next
xExcel.DisplayAlerts = True
xExcel.Quit
xFileArr() = GetFiles(xPath)
'Merge Documents
For I = 0 To UBound(xFileArr()) - 1
    xExt = SplitPath(xFileArr(I), 2)
    If (xExt = ".docx") Or (xExt = ".doc") Or (xExt = ".docm") Or (xExt = ".dot") Or _
       (xExt = ".dotm") Or (xExt = ".dotx") Then
        MergeDoc xWdApp, xPath & xFileArr(I), xNewDoc
        Kill xPath & xFileArr(I)
    End If
Next
xNewDoc.Sections.Item(1).Range.Delete wdCharacter, 1
xNewDoc.SaveAs2 xPDFSavePath, wdFormatPDF
xNewDoc.Close wdDoNotSaveChanges, wdOriginalDocumentFormat, False
xWdApp.Quit
Set xMail = Nothing
Set xNameSpace = Nothing
Set xFSysObj = Nothing
MsgBox "Merged successfully", vbInformation + vbOKOnly
End Sub

Public Function SplitPath(FullPath As String, ResultFlag As Integer) As String
Dim SplitPos As Integer, DotPos As Integer
SplitPos = InStrRev(FullPath, "/")
DotPos = InStrRev(FullPath, ".")
Select Case ResultFlag
Case 0
   SplitPath = Left(FullPath, SplitPos - 1)
Case 1
   If DotPos = 0 Then DotPos = Len(FullPath) + 1
   SplitPath = Mid(FullPath, SplitPos + 1, DotPos - SplitPos - 1)
Case 2
   If DotPos = 0 Then DotPos = Len(FullPath)
   SplitPath = Mid(FullPath, DotPos)
Case Else
   Err.Raise vbObjectError + 1, "SplitPath Function", "Invalid Parameter!"
End Select
End Function
  
Function CleanFileName(StrText As String) As String
Dim xStripChars As String
Dim xLen As Integer
Dim I As Integer
xStripChars = "/\[]:=," & Chr(34)
xLen = Len(xStripChars)
StrText = Trim(StrText)
For I = 1 To xLen
StrText = Replace(StrText, Mid(xStripChars, I, 1), "")
Next
CleanFileName = StrText
End Function

Function GetFiles(xFldPath As String) As String()
On Error Resume Next
Dim xFile As String
Dim xFileArr() As String
Dim xArr() As String
Dim I, x As Integer
x = 0
ReDim xFileArr(1)
xFileArr(1) = xFldPath '& "\"
xFile = Dir(xFileArr(1) & "*.*")
Do Until xFile = ""
    x = x + 1
    xFile = Dir
Loop
ReDim xArr(0 To x)
x = 0
xFile = Dir(xFileArr(1) & "*.*")
Do Until xFile = ""
    xArr(x) = xFile
    x = x + 1
    xFile = Dir
Loop
GetFiles = xArr()
End Function

Sub MergeDoc(WdApp As Word.Application, xFileName As String, Doc As Document)
Dim xNewDoc As Document
Dim xSec As Section
    Set xNewDoc = WdApp.Documents.Open(filename:=xFileName, Visible:=False)
    Set xSec = Doc.Sections.Add
    xNewDoc.Content.Copy
    xSec.PageSetup = xNewDoc.PageSetup
    xSec.Range.PasteAndFormat wdFormatOriginalFormatting
    xNewDoc.Close
End Sub

3. Cliquez sur Outils > Références pour ouvrir la boîte de dialogue Références. Cochez les cases Bibliothèque d'objets Microsoft Excel, Microsoft Scripting Runtime et Bibliothèque d'objets Microsoft Word, puis cliquez sur le bouton OK. Voir capture d'écran :

the step 1 about saving email attachments as single pdf

4. Appuyez sur la touche F5 ou cliquez sur le bouton Exécuter pour exécuter le code. Une boîte de dialogue Enregistrer sous apparaît, veuillez spécifier un dossier pour enregistrer le fichier, donnez ensuite un nom au fichier PDF et cliquez sur le bouton Enregistrer. Voir capture d'écran :

the step 2 about saving email attachments as single pdf

5. Une boîte de dialogue Microsoft Outlook apparaît, veuillez cliquer sur le bouton OK.

the step 3 about saving email attachments as single pdf

L'email sélectionné avec toutes ses pièces jointes est maintenant enregistré dans un seul fichier PDF.

Remarque : Ce script VBA ne fonctionne que pour les pièces jointes Microsoft Word et Excel.


Enregistrez facilement les emails sélectionnés dans différents formats de fichiers dans Outlook :

Avec l'utilitaire Enregistrement en bloc de Kutools pour Outlook, vous pouvez facilement enregistrer plusieurs emails sélectionnés en tant que fichiers individuels au format HTML, TXT, document Word, fichier CSV ainsi que PDF dans Outlook comme le montre la capture d'écran ci-dessous. Téléchargez dès maintenant la version gratuite de Kutools pour Outlook !

the step 1 about saving email attachments as single pdf

Articles connexes :


Meilleurs outils de productivité pour Office

Dernière nouvelle : Kutools pour Outlook lance sa version gratuite !

Découvrez le tout nouveau Kutools pour Outlook avec plus de100 fonctionnalités incroyables ! Cliquez pour télécharger dès maintenant !

🤖 Kutools IA : Exploite une technologie avancée d’IA pour gérer les e-mails en toute simplicité, notamment pour répondre, résumer, optimiser, étendre, traduire et rédiger des e-mails.

📧 Automatisation des E-mails : Réponse automatique (disponible pour POP et IMAP) / Programmer l’envoi d’un e-mail / CC/BCC automatique par règle lors de l’envoi / Transfert automatique (règle avancée) / Ajouter automatiquement une salutation / Diviser automatiquement les e-mails multi-destinataires en messages individuels ...

📨 Gestion des E-mails : Rappeler lemail / Bloquer les e-mails frauduleux par objet et autres critères / Supprimer les doublons / Recherche Avancée / Organiser les dossiers ...

📁 Pièces jointes Pro : Enregistrement en lot / Détachement en lot / Compression en lot / Enregistrer automatiquement / Détachement automatique / Compression automatique ...

🌟 Interface magique : 😊Plus d’emojis élégants et amusants / Vous rappelle lorsque des e-mails importants arrivent / Réduire Outlook au lieu de fermer ...

👍 Fonctions en un clic : Répondre à tous avec pièces jointes / E-mails anti-phishing / 🕘Afficher le fuseau horaire de l’expéditeur ...

👩🏼‍🤝‍👩🏻 Contacts & Calendrier : Ajouter en lot des contacts à partir des e-mails sélectionnés / Diviser un groupe de contacts en groupes individuels / Supprimer le rappel d’anniversaire ...

Utilisez Kutools dans votre langue préférée – prend en charge l’Anglais, l’Espagnol, l’Allemand, le Français, le Chinois et plus de40 autres !

Débloquez instantanément Kutools pour Outlook en un seul clic. N’attendez pas, téléchargez dès maintenant pour gagner en efficacité !

kutools for outlook features1 kutools for outlook features2

🚀 Téléchargement en un clic — Obtenez tous les compléments Office

Recommandé vivement : Kutools pour Office (5-en-1)

Un clic pour télécharger cinq installateurs en une seule fois — Kutools pour Excel, Outlook, Word, PowerPoint et Office Tab Pro. Cliquez pour télécharger dès maintenant !

  • Praticité en un clic : téléchargez les cinq packages d’installation en une seule action.
  • 🚀 Prêt pour toutes les tâches Office : installez les compléments dont vous avez besoin, quand vous en avez besoin.
  • 🧰 Inclus : Kutools pour Excel / Kutools pour Outlook / Kutools pour Word / Office Tab Pro / Kutools pour PowerPoint