Saltar al contenido principal

¿Cómo usar el botón de comando para guardar la hoja de trabajo activa como archivo PDF en Excel?

Mientras trabaja en Microsoft Excel, puede enfrentar el problema de guardar la hoja de trabajo activa como archivo PDF. En este artículo, puede aprender cómo guardar la hoja de trabajo activa como archivo PDF con código VBA a través de un botón de comando. Y si también desea guardar un rango o cada hoja de trabajo en el libro activo como un archivo PDF individual, este artículo también puede ayudarlo.

Use el botón de comando para guardar la hoja de trabajo activa como archivo PDF con código VBA
Guarde fácilmente cada hoja de trabajo activa o como un archivo PDF individual con Kutools para Excel


Use el botón de comando para guardar la hoja de trabajo activa como archivo PDF con código VBA

Puede ejecutar el siguiente código VBA para guardar una hoja de trabajo activa como archivo PDF haciendo clic en un botón de comando. Haz lo siguiente.

1. En primer lugar, debe crear una carpeta llamada PDF para guardar su nuevo archivo PDF convertido. Aquí creo esta carpeta en mi disco local (C :).

2. Inserte un botón de comando haciendo clic en Developer > recuadro > Botón de comando (control ActiveX). Ver captura de pantalla:

2. Luego dibuje un Botón de Comando en la hoja de trabajo que necesita para agregar nuevas filas, haga clic derecho en el Botón de Comando y haga clic en Propiedades desde el menú contextual.

3. En el Propiedades cuadro de diálogo, ingrese el texto mostrado del botón de comando en el Subtítulo caja debajo del En la Categoría pestaña y luego cierre el cuadro de diálogo.

Puede ver que el texto mostrado del botón de comando cambia como se muestra a continuación.

4. Haga clic con el botón derecho en el Botón de comando nuevamente y luego haga clic en Ver código desde el menú contextual.

5. En la apertura Microsoft Visual Basic para aplicaciones ventana, reemplace el código original en la ventana Código con el siguiente código VBA.

Código VBA: botón de comando para guardar la hoja de trabajo activa como PDF

Private Sub CommandButton1_Click()
    Application.ScreenUpdating = False
    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
            Filename:="C:\PDF\Export.pdf", _
            OpenAfterPublish:=False
    Application.ScreenUpdating = True
End Sub

Note: En el código, CommandButton1 es el nombre del botón de comando que usará para guardar la hoja activa como archivo PDF. "C: \ PDF \ Export.pdf" es la ruta y el nombre del archivo PDF guardado.

6. presione el otro + Q teclas simultáneamente para cerrar el Microsoft Visual Basic para aplicaciones ventana. Entonces apaga el Modo de diseño bajo el Developer .

Ahora, haga clic en el Botón de comando, la hoja de trabajo activa se guardará como un archivo PDF llamado Exportar y se ubicará en la ubicación especificada.


Guarde cada hoja de trabajo como un archivo PDF individual de un libro activo con Kutools para Excel

Aquí recomiendo el Libro de trabajo dividido utilidad de Kutools for Excel para guardar fácilmente la hoja de trabajo activa como un archivo PDF. Además, también puede guardar cada hoja de trabajo en el libro de trabajo actual como un archivo PDF individual con esta utilidad.

Antes de aplicar Kutools for Excel, Por favor descargarlo e instalarlo en primer lugar.

1. En el libro de trabajo, debe guardar cada hoja de trabajo como un archivo PDF individual y luego hacer clic en Kutools Más > Libro de trabajo > Libro de trabajo dividido. Ver captura de pantalla:

2. En el Libro de trabajo dividido cuadro de diálogo, configure de la siguiente manera:

2.1) Solo verifique el nombre de la hoja activa en el Nombre de la hoja de trabajo caja;
2.2) Seleccionar PDF (* .pdf) Opción de la Guardar como tipo la lista desplegable;
2.3) Haga clic en Mini Split botón, luego un Seleccionar carpeta aparece un cuadro de diálogo, especifique una carpeta para guardar el archivo PDF;

Luego, la hoja de trabajo seleccionada se guarda como archivo PDF inmediatamente.

Notas:

1. Puede marcar varios nombres de hojas de trabajo en el cuadro Nombre de la hoja de trabajo para guardarlos como archivos PDF individuales a la vez;
2. A excepción de guardar la hoja de trabajo como archivos pdf, puede guardar las hojas de trabajo como txt. o csv. archivo como lo necesite.

  Si desea tener una prueba gratuita (30 días) de esta utilidad, haga clic para descargarloy luego vaya a aplicar la operación según los pasos anteriores.


Demostración: guarde la selección o cada hoja de trabajo como PDF con Kutools para Excel


Artículos relacionados:

Las mejores herramientas de productividad de oficina

🤖 Asistente de IA de Kutools: Revolucionar el análisis de datos basado en: Ejecución inteligente   |  Generar codigo  |  Crear fórmulas personalizadas  |  Analizar datos y generar gráficos  |  Invocar funciones de Kutools...
Características populares: Buscar, resaltar o identificar duplicados   |  Eliminar filas en blanco   |  Combine columnas o celdas sin perder datos   |   Ronda sin fórmula ...
Super búsqueda: Búsqueda virtual de criterios múltiples    Búsqueda V de valores múltiples  |   VLookup en varias hojas   |   Búsqueda difusa ....
Lista desplegable avanzada: Crear rápidamente una lista desplegable   |  Lista desplegable dependiente   |  Lista desplegable de selección múltiple ....
Administrador de columnas: Agregar un número específico de columnas  |  Mover columnas  |  Toggle Estado de visibilidad de columnas ocultas  |  Comparar rangos y columnas ...
Características destacadas: Enfoque de cuadrícula   |  Vista de diseño   |   Gran barra de fórmulas    Administrador de hojas y libros de trabajo   |  Biblioteca de Recursos (Texto automático)   |  Selector de fechas   |  Combinar hojas de trabajo   |  Cifrar/descifrar celdas    Enviar correos electrónicos por lista   |  Súper filtro   |   Filtro especial (filtro negrita/cursiva/tachado...) ...
Los 15 mejores conjuntos de herramientas12 Texto Herramientas (Añadir texto, Quitar caracteres, ...)   |   50+ Tabla Tipos (Diagrama de Gantt, ...)   |   40+ Práctico Fórmulas (Calcular la edad según el cumpleaños, ...)   |   19 Inserción Herramientas (Insertar código QR, Insertar imagen desde la ruta, ...)   |   12 Conversión Herramientas (Números a palabras, Conversión de Moneda, ...)   |   7 Fusionar y dividir Herramientas (Filas combinadas avanzadas, Células partidas, ...)   |   ... y más

Mejore sus habilidades de Excel con Kutools for Excel y experimente la eficiencia como nunca antes. Kutools for Excel ofrece más de 300 funciones avanzadas para aumentar la productividad y ahorrar tiempo.  Haga clic aquí para obtener la función que más necesita...

Descripción


Office Tab lleva la interfaz con pestañas a Office y hace que su trabajo sea mucho más fácil

  • Habilite la edición y lectura con pestañas en Word, Excel, PowerPoint, Publisher, Access, Visio y Project.
  • Abra y cree varios documentos en nuevas pestañas de la misma ventana, en lugar de en nuevas ventanas.
  • ¡Aumenta su productividad en un 50% y reduce cientos de clics del mouse todos los días!
Comments (33)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
Ich nutze diese Zeilen und das funktioniert auch gut, mein Problem ist nur, sollte diese Datei bereits vorhanden sein, WIRD diese einfach überschrieben!
Wie kann ich das vermeiden, es sollte eine Meldung kommen, Datei existiert bereits und es soll beendet werden?


Private Sub CommandButton1_Click()
Application.ScreenUpdating = False
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:="X:\firmen\Buchhaltung\Rechnungs-Kopie_Ackermann Service GmbH\2022\RK-Abrechnung\" & ActiveSheet.Range("G1") & ".pdf", _
OpenAfterPublish:=True
Application.ScreenUpdating = True
End Sub
This comment was minimized by the moderator on the site
Hi Sascha,
The following VBA code can help. Please give it a try.

Private Sub CommandButton1_Click()
'Updated by Extendoffice 20221230
    Dim xPDFName As String
    Dim xPDFPath As String
    Dim xObjFS As Object
    Dim xNum As Integer
    Dim xStr As String
    
    xPDFName = "Export" 'The file name
    xPDFPath = "D:\work\Jan\test\" 'The file path
    Application.ScreenUpdating = True
    On Error Resume Next
    Set xObjFS = CreateObject("Scripting.FileSystemObject")
    xStr = xPDFPath & xPDFName & ".pdf"
    xNum = 1
    If xObjFS.FileExists(xStr) Then
    xResponse = MsgBox("The file already exists, do you want to overwrite it?", vbYesNo, "www.extendoffice.com", "", 0)
       If xResponse <> vbYes Then
       Exit Sub
      End If
    End If
    Application.ScreenUpdating = False
    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
            FileName:=xStr, _
            OpenAfterPublish:=False
    Application.ScreenUpdating = True
End Sub
This comment was minimized by the moderator on the site
Ich nutze diese Zeilen und das funktioniert auch gut, mein Problem ist nur, sollte diese Datei bereits vorhanden sein, wird diese einfach überschrieben!
Wie kann ich das vermeiden, es sollte eine Meldung kommen, Datei existiert bereits und es soll beendet werden?
This comment was minimized by the moderator on the site
When I run the below it creates a local version of the PDF automatically - how do I stop this from automatically saving?

Private Sub CommandButton1_Click()
Application.ScreenUpdating = False
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
OpenAfterPublish:=True
Application.ScreenUpdating = True
End Sub
This comment was minimized by the moderator on the site
Hi James,
Do you want to pop up a window to select a folder to save the PDF file manually?
This comment was minimized by the moderator on the site
Hi Crystal, ideally yes so I can then choose where to save the PDF.
This comment was minimized by the moderator on the site
H James,

The following VBA code can help you solve the problem.
Note: You can't handle both the destination and the file name at the same time. After adding the following VBA code, when you click the button, a dialog box will pop up for you to select a destination folder. After selecting a destination folder, a box will pop up for you to give a name to the PDF file.

Private Sub CommandButton1_Click()
'Updated by Extendoffice 20221223
    Dim xDlg As FileDialog
    Dim xFolder As Variant
    Set xDlg = Application.FileDialog(msoFileDialogFolderPicker)
    Dim xStrName As String
    If xDlg.Show <> -1 Then Exit Sub
    
    xFolder = xDlg.SelectedItems(1)
    
    xStart = InputBox("file name", "KuTools for Excel", ActiveSheet.Name & ".pdf")

    Application.ScreenUpdating = False

    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
            Filename:=xFolder & "\" & xStart, _
            OpenAfterPublish:=False
    Application.ScreenUpdating = True

End Sub
This comment was minimized by the moderator on the site
Whenever I run this it saves a PDF to my local drive where the excel sheets saved, how do I stop this from auto saving?

Private Sub CommandButton1_Click()
Application.ScreenUpdating = False
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
OpenAfterPublish:=True
Application.ScreenUpdating = True
End Sub
This comment was minimized by the moderator on the site
Hi Team,

Just wondering if anyone could help with changing the destination of the created file to any user's desktop? My compnay doesn't allow access to C: so the script doesn't work.

MANY MANY MANY thanks!
This comment was minimized by the moderator on the site
Hi Ben Stoddart,
You just need to open any folder on your desktop and copy the folder path in the address box, then replace the folder path in the VBA code with the path you copied.
Here is the new Filename line (please replace the Username with your own username), Export.pdf is the name and the file extension of the PDF file:
Filename:="C:\Users\Username\Desktop\PDF\Export.pdf", _
This comment was minimized by the moderator on the site
Goededag

is het mogelijk om een filmpje of een voorbeeld excelblad te maken voor de Command-Knop Om Een ​​Actief Werkblad Op Te Slaan Als PDF-Bestand Met VBA-Code.
kom er niet helemaal uit met de codes.
alvast bedankt
This comment was minimized by the moderator on the site
Hi max,
Sorry I don't understand what you mean. You may need to attach a screenshot of what you are trying to do. Sorry for the inconvenience.
This comment was minimized by the moderator on the site
Что это за кнопка - "другой" + Q клавиши одновременно" ? Не поняла что нажимать, подскажите, пожалуйста
This comment was minimized by the moderator on the site
Hi Диана,
It is the "Alt" key on your keyboard. Microsoft Excel allows users to press the "Alt" + "Q" keys to close the Microsoft Visual Basic for Applications window and return to the worksheet.
This comment was minimized by the moderator on the site
Hallo,

ich nutze diese Zeilen und möchte das eine Zelle als Dateiname verwenden wird!
Kann mir jemand ein Tipp geben?


Private Sub CommandButton1_Click()
Application.ScreenUpdating = False
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:="c:/" & G3 & ".pdf", _
OpenAfterPublish:=False
Application.ScreenUpdating = True
End Sub
This comment was minimized by the moderator on the site
Hi Sascha,
The following code can help. Before applying the code, please change 'C:\Users\Win10x64Test\Documents\PDF' in the fourth line to you own destination folder path.
Private Sub CommandButton1_Click()
'Updated by Extendoffice 20220929
    Application.ScreenUpdating = False
    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
            Filename:="C:\Users\Win10x64Test\Documents\PDF\" & Range("G3").Value, _
            OpenAfterPublish:=False
    Application.ScreenUpdating = True
End Sub
This comment was minimized by the moderator on the site
Hallo,

kann jemand mir helfen?

Ich nutze diese Zeilen und möchte jedoch, das aus dem Blatt ein Zellenwert als Dateiname gespeichert wird:

Private Sub CommandButton1_Click()
Application.ScreenUpdating = False
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:="C:\PDF\Export.pdf", _
OpenAfterPublish:=False
Application.ScreenUpdating = True
End Sub

Danke
This comment was minimized by the moderator on the site
ive followed the code, this is what i have:

Private Sub CommandButton2_Click()
Application.ScreenUpdating = False
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=Range("P2"), _
OpenAfterPublish:=True
Application.ScreenUpdating = True
End Sub

i need the file to save to the location that the orignal file is located. also need a copy of the excel file to save aswell with the same name.
This comment was minimized by the moderator on the site
Hi Matt Bentley,
The code works perfectly. Thank you for sharing.
There are no comments posted here yet
Load More
Please leave your comments in English
Posting as Guest
×
Rate this post:
0   Characters
Suggested Locations