¿Cómo convertir o guardar un correo electrónico y sus adjuntos en un único archivo PDF en Outlook?
Este artículo trata sobre cómo guardar un mensaje de correo electrónico y todos los archivos adjuntos que contiene en un único archivo PDF en Outlook.
Convertir o guardar un correo electrónico y sus adjuntos en un único archivo PDF con código VBA
Convertir o guardar un correo electrónico y sus adjuntos en un único archivo PDF con código VBA
Por favor, sigue los siguientes pasos para guardar un correo electrónico con todos sus adjuntos en un único archivo PDF en Outlook.
1. Selecciona un correo electrónico con adjuntos que desees guardar en un único archivo PDF, y luego presiona las teclas Alt + F11 para abrir la ventana de Microsoft Visual Basic para Aplicaciones.
2. En la ventana de Microsoft Visual Basic para Aplicaciones, haz clic en Insertar > Módulo. Luego copia el siguiente código VBA en la ventana del Módulo.
Código VBA: Guardar correo electrónico y adjunto en un único archivo 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. Haz clic en Herramientas > Referencias para abrir el cuadro de diálogo Referencias. Marca las casillas de la Biblioteca de Objetos de Microsoft Excel, Microsoft Scripting Runtime y Biblioteca de Objetos de Microsoft Word, y luego haz clic en el botón Aceptar. Ver captura de pantalla:

4. Presiona la tecla F5 o haz clic en el botón Ejecutar para ejecutar el código. Luego aparecerá un cuadro de diálogo Guardar como, por favor, especifica una carpeta para guardar el archivo, da un nombre al archivo PDF y haz clic en el botón Guardar. Ver captura de pantalla:

5. Luego aparecerá un cuadro de diálogo de Microsoft Outlook, por favor, haz clic en el botón Aceptar.

Ahora el correo electrónico seleccionado con todos sus adjuntos se ha guardado en un único archivo PDF.
Nota: Este script VBA solo funciona para adjuntos de Microsoft Word y Excel.
Guardar fácilmente correos electrónicos seleccionados en diferentes formatos de archivo en Outlook:
Con la utilidad Guardado Masivo de Kutools para Outlook, puedes guardar fácilmente varios correos electrónicos seleccionados como archivos individuales en formato HTML, TXT, documento de Word, archivo CSV así como archivo PDF en Outlook, como se muestra en la siguiente captura de pantalla. ¡Descarga ahora la versión gratuita de Kutools para Outlook!

Artículos relacionados:
- ¿Cómo usar el Botón de Comando para guardar la hoja de trabajo activa como archivo PDF en Excel?
- ¿Cómo guardar una hoja de trabajo como archivo PDF y enviarla como adjunto a través de Outlook?
- ¿Cómo guardar la selección o todo el libro de trabajo como PDF en Excel?
Las mejores herramientas de productividad para Office
Últimas noticias: ¡Kutools para Outlook lanza su versión gratuita!
Descubre la nueva versión GRATUITA de Kutools para Outlook con más de70 funciones increíbles, ¡para que la disfrutes PARA SIEMPRE! ¡Haz clic para descargar ahora!
📧 Automatización de Email: Respuesta automática (Disponible para POP e IMAP) / Programar envío de correos / CC/BCC automático por regla al enviar correo / Reenvío automático (Regla avanzada) / Agregar saludo automáticamente / Dividir automáticamente emails con múltiples destinatarios en mensajes individuales...
📨 Gestión de Email: Recuperar correo electrónico / Bloquear correos fraudulentos por asunto y otros criterios / Eliminar correos electrónicos duplicados / Búsqueda Avanzada / Organizar carpetas...
📁 Adjuntos Pro: Guardar en lote / Desanexar en lote / Comprimir en lote / Guardar automáticamente / Desconectar automáticamente / Auto Comprimir...
🌟 Magia en la interfaz: 😊Más emojis bonitos y modernos / Avisos cuando llegan correos importantes / Minimiza Outlook en vez de cerrarlo...
👍 Funciones de un solo clic: Responder a Todos con Adjuntos / Correos electrónicos anti-phishing / 🕘Mostrar la zona horaria del remitente...
👩🏼🤝👩🏻 Contactos y Calendario: Agregar contactos en lote desde correos seleccionados / Dividir un grupo de contactos en grupos individuales / Eliminar recordatorio de cumpleaños...

