* Este es un mensaje de invitado de Ryan Wells, otro blogger y un brillante desarrollador de VBA. *
Si trabaja con Excel, sin duda se le ha pedido que cree resúmenes de su trabajo.
Informes de ventas, facturas, previsiones, horarios, así lo nombra.
Sabéis qué tienen en común todos estos documentos? Quedan muy bien en formato PDF. Sabes qué más? En la gestión le encantan los archivos PDF.
Convierta Excel a PDF
En este tutorial, te mostraré cómo utilizar Excel VBA para convertir todo tipo de objetos Excel a PDF:
Voy a presentar cada una de las macros con algún comentario. De este modo, podrá encontrarlos rápidamente, copiarlos en su editor VBA y utilizarlos.
Cuando ejecute cualquiera de estas macros, aparecerá un cuadro de diálogo Guardar como preguntándoos que desea guardar el PDF. El nombre por defecto incluye la fecha y la marca de tiempo cuando voy ejecutar la macro en formato aaaammdd_hhmmss.
Vamos bien.
A continuación las macros:
Selección de impresión en PDF
Este es mi favorito personal. Esta macro convertirá las celdas que ha seleccionado activamente en un PDF.
Si sólo tiene una celda seleccionada, la macro VBA es lo suficientemente inteligente para darse cuenta de que probablemente no desea convertir sólo una celda, por lo que le pedirá que elija el intervalo que desea convertir:
Sub PrintSelectionToPDF() 'SUBROUTINE: PrintSelectionToPDF 'DEVELOPER: Ryan Wells 'DESCRIPTION: Print your currently selected range to a PDF Dim ThisRng As Range Dim strfile As String Dim myfile As Variant If Selection.Count = 1 Then Set ThisRng = Application.InputBox("Select a range", "Get Range", Type:=8) Else Set ThisRng = Selection End If 'Prompt for save location strfile = "Selection" & "_" _ & Format(Now(), "yyyymmdd_hhmmss") _ & ".pdf" strfile = ThisWorkbook.Path & "" & strfile myfile = Application.GetSaveAsFilename _ (InitialFileName:=strfile, _ FileFilter:="PDF Files (*.pdf), *.pdf", _ Title:="Select Folder and File Name to Save as PDF") If myfile <> "False" Then 'save as PDF ThisRng.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _ myfile, Quality:=xlQualityStandard, IncludeDocProperties:=True, _ IgnorePrintAreas:=False, OpenAfterPublish:=True Else MsgBox "No File Selected. PDF will not be saved", vbOKOnly, "No File Selected" End If End Sub
Una vez seleccione el intervalo y haga clic en Aceptar, se mostrará un cuadro de diálogo que permite seleccionar que desea guardar el PDF.
Seleccionará automáticamente la fecha y la hora del reloj del sistema y lo añadirá al nombre del archivo.
Imprima una tabla en PDF
Muchos usuarios avanzados de Excel almacenan sus datos en tablas organizadas. De hecho, al mismo Sumido Bansal le gustan tanto las tablas de Excel que las llama tesoro oculto a Excel.
Esta macro imprime una tabla que elija en un PDF. Cuando ejecute la macro, le pedirá el nombre de la tabla que desea guardar.
Sub PrintTableToPDF() 'SUBROUTINE: PrintTableToPDF 'DEVELOPER: Ryan Wells 'DESCRIPTION: Print a table of your choosing to a PDF Dim strfile As String Dim myfile As Variant Dim strTable As String, r As Range Application.ScreenUpdating = False 'Enter the table name you want to save strTable = InputBox("What's the name of the table you want to save?", "Enter Table Name") 'Table you want to save If Trim(strTable) = "" Then Exit Sub 'Prompt for save location strfile = strTable & "_" _ & Format(Now(), "yyyymmdd_hhmmss") _ & ".pdf" strfile = ThisWorkbook.Path & "" & strfile myfile = Application.GetSaveAsFilename _ (InitialFileName:=strfile, _ FileFilter:="PDF Files (*.pdf), *.pdf", _ Title:="Select Folder and File Name to Save as PDF") If myfile <> "False" Then 'save as PDF Range(strTable).ExportAsFixedFormat Type:=xlTypePDF, Filename:=myfile, Quality:=xlQualityStandard, _ IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=True Else MsgBox "No File Selected. PDF will not be saved", vbOKOnly, "No File Selected" End If Application.DisplayAlerts = False LetsContinue: With Application .ScreenUpdating = True .DisplayAlerts = True End With Exit Sub End Sub
Una vez introduzca el nombre de la tabla y haga clic en Aceptar, se mostrará un cuadro de diálogo que permite seleccionar que desea guardar el PDF.
Seleccionará automáticamente la fecha y la hora del reloj del sistema y lo añadirá al nombre del archivo.
Imprima todas las mesas para separar PDF
Si su hoja de cálculo tiene varias mesas y debe guardar cada una en un PDF separado, puede ejecutar este código VBA.
Cuando ejecute esta macro, aparecerá un cuadro de diálogo que le pedirá que seleccione la carpeta donde desea guardar los PDF.
Una vez elija la carpeta, la macro guardará cada mesa en un PDF con el nombre de la tabla que aparece convenientemente en el título del PDF.
Sub PrintAllTablesToPDFs() 'SUBROUTINE: PrintAllTablesToPDFs 'DEVELOPER: Ryan Wells 'DESCRIPTION: Print each table in your spreadsheet to a different PDF Dim strTables() As String Dim strfile As String Dim ch As Object, sh As Worksheet Dim icount As Integer Dim myfile As Variant Dim tbl As ListObject Dim sht As Worksheet With Application.FileDialog(msoFileDialogFolderPicker) .Title = "Where do you want to save your PDF?" .ButtonName = "Save Here" .InitialFileName = ThisWorkbook.Path If .Show = -1 Then ' if OK is pressed sfolder = .SelectedItems(1) Else End End If End With For Each sht In ThisWorkbook.Worksheets For Each tbl In sht.ListObjects myfile = ThisWorkbook.Name & "" & tbl.Name & "" _ & Format(Now(), "yyyymmdd_hhmmss") _ & ".pdf" myfile = sfolder & "" & myfile sht.Range(tbl.Name).ExportAsFixedFormat Type:=xlTypePDF, Filename:= _ myfile, Quality:=xlQualityStandard, IncludeDocProperties:=True, _ IgnorePrintAreas:=False, OpenAfterPublish:=True Next tbl Next sht End Sub
Imprima todas las hojas en un solo PDF
No sé vosotros, pero en mi línea de trabajo debemos conservar copias en PDF de casi todos nuestros hojas de cálculo. Añadimos las copias PDF de nuestras hojas de cálculo a nuestros cálculos de diseño. Estos archivos PDF antes se convertían en microfichas y se guardaban para conservarlos a largo plazo. Ya sabes, por si el apocalipsis pasó.
Si se encuentra en una situación similar, es bueno poder convertir automáticamente todas las hojas de la hoja de cálculo en un PDF. Aquí hay una macro VBA que hará esto:
Sub PrintAllSheetsToPDF() 'SUBROUTINE: PrintAllSheetsToPDF 'DEVELOPER: Ryan Wells 'DESCRIPTION: Combine all your worksheets into one PDF Dim strSheets() As String Dim strfile As String Dim sh As Worksheet Dim icount As Integer Dim myfile As Variant 'Save Chart Sheet names to an Array For Each sh In ActiveWorkbook.Worksheets If sh.Visible = xlSheetVisible Then ReDim Preserve strSheets(icount) strSheets(icount) = sh.Name icount = icount + 1 End If Next sh If icount = 0 Then 'No charts found. Punch error MsgBox "A PDF cannot be created because no sheets were found.", , "No Sheets Found" Exit Sub End If 'Prompt for save location strfile = "Sheets" & "_" _ & Format(Now(), "yyyymmdd_hhmmss") _ & ".pdf" strfile = ThisWorkbook.Path & "" & strfile myfile = Application.GetSaveAsFilename _ (InitialFileName:=strfile, _ FileFilter:="PDF Files (*.pdf), *.pdf", _ Title:="Select Folder and File Name to Save as PDF") If myfile <> "False" Then 'save as PDF ThisWorkbook.Sheets(strSheets).Select ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _ myfile, Quality:=xlQualityStandard, IncludeDocProperties:=True, _ IgnorePrintAreas:=False, OpenAfterPublish:=True Else MsgBox "No File Selected. PDF will not be saved", vbOKOnly, "No File Selected" End If End Sub
Imprimir hojas gráficos a PDF
Esta macro convierte todos sus hojas de gráficos en un PDF, pero no sus objetos. Para hojas de gráficos, quiero decir los gráficos que tienen su propia pestaña en la lista de pestañas de la hoja de cálculo:
Sub PrintChartSheetsToPDF() 'SUBROUTINE: PrintChartSheetsToPDF 'DEVELOPER: Ryan Wells 'DESCRIPTION: Combine all chart sheets into one PDF Dim strSheets() As String Dim strfile As String Dim ch As Object, sh As Worksheet Dim icount As Integer Dim myfile As Variant 'Save Chart Sheet names to an Array For Each ch In ActiveWorkbook.Charts ReDim Preserve strSheets(icount) strSheets(icount) = ch.Name icount = icount + 1 Next ch If icount = 0 Then 'No charts found. Punch error MsgBox "A PDF cannot be created because no Chart Sheets were found.", , "No Chart Sheets Found" Exit Sub End If 'Prompt for save location strfile = "Charts" & "_" _ & Format(Now(), "yyyymmdd_hhmmss") _ & ".pdf" strfile = ThisWorkbook.Path & "" & strfile myfile = Application.GetSaveAsFilename _ (InitialFileName:=strfile, _ FileFilter:="PDF Files (*.pdf), *.pdf", _ Title:="Select Folder and File Name to Save as PDF") If myfile <> "False" Then 'save as PDF ThisWorkbook.Sheets(strSheets).Select ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _ myfile, Quality:=xlQualityStandard, IncludeDocProperties:=True, _ IgnorePrintAreas:=False, OpenAfterPublish:=True Else MsgBox "No File Selected. PDF will not be saved", vbOKOnly, "No File Selected" End If End Sub
Imprimir los objetos del gráfico en PDF
Esta macro guarda todos los gráficos normales (objetos de gráficos) en un solo PDF. Independientemente de la hoja de cálculo en la que esté el gráfico, se tomará y se guardará en un PDF.
Sólo habrá un gráfico por página en el PDF final.
Sub PrintChartsObjectsToPDF() 'SUBROUTINE: PrintChartsObjectsToPDF 'DEVELOPER: Ryan Wells 'DESCRIPTION: Combine all chart objects into one PDF Dim ws As Worksheet, wsTemp As Worksheet Dim chrt As ChartObject Dim tp As Long Dim strfile As String Dim myfile As Variant Application.ScreenUpdating = False Set wsTemp = Sheets.Add tp = 10 With wsTemp For Each ws In ActiveWorkbook.Worksheets If ws.Name = wsTemp.Name Then GoTo nextws: For Each chrt In ws.ChartObjects chrt.Copy wsTemp.Range("A1").PasteSpecial Selection.Top = tp Selection.Left = 5 If Selection.TopLeftCell.Row > 1 Then ActiveSheet.Rows(Selection.TopLeftCell.Row).PageBreak = xlPageBreakManual End If tp = tp + Selection.Height + 50 Next nextws: Next ws End With 'Prompt for save location strfile = "Charts" & "_" _ & Format(Now(), "yyyymmdd_hhmmss") _ & ".pdf" strfile = ActiveWorkbook.Path & "" & strfile myfile = Application.GetSaveAsFilename _ (InitialFileName:=strfile, _ FileFilter:="PDF Files (*.pdf), *.pdf", _ Title:="Select Folder and File Name to Save as PDF") If myfile <> False Then 'save as PDF wsTemp.ExportAsFixedFormat Type:=xlTypePDF, Filename:=myfile, Quality:=xlQualityStandard, _ IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=True 'Else ' MsgBox "No File Selected. PDF will not be saved", vbOKOnly, "No File Selected" End If Application.DisplayAlerts = False wsTemp.Delete With Application .ScreenUpdating = True .DisplayAlerts = True End With Exit Sub End Sub
Si tiene alguna pregunta, dejar ir a la sección de comentarios, donde Ryan y yo os esperaremos.
También te pueden gustar los siguientes tutoriales de Excel:
Sobre el autor: Ryan Wells es ingeniero nuclear y desarrollador profesional de VBA. Publica sus tutoriales Excel-VBA fáciles de entender para ayudar a otros a escribir mejores macros. Además de enseñar VBA, Ryan es el desarrollador principal de varios complementos de Excel. Puede encontrar sus tutoriales a WellsR.com.