VBA - Microsoft Print to PDF - Set Save As Path Same As Workbook Location

69 Views Asked by At

So I have an Excel VBA Macro that helps me save the workbook as a PDF...it is called like this...

Application.ActivePrinter = FindPrinter("Microsoft Print to PDF")

It will successfully open the save as PDF prompt but I need it to default to save in the path as the Workbook/Excel sheet is and it is based upon the job number.

\fileserver\drafting\MBS_JOBS\JobNumber

How can I tell Microsoft Print to PDF to save where the Excel sheet was opened from?

1

There are 1 best solutions below

1
Freddy Reyes On
Sub GuardarComoPDF()
    ' Obtener la ruta del archivo del libro de trabajo
    Dim rutaArchivo As String
    rutaArchivo = ThisWorkbook.Path
    
    ' Verificar si se obtuvo una ruta válida
    If rutaArchivo <> "" Then
        ' Configurar la impresora predeterminada como "Microsoft Print to PDF"
        Application.ActivePrinter = FindPrinter("Microsoft Print to PDF")
        
        ' Construir la ruta completa del archivo PDF
        Dim rutaPDF As String
        rutaPDF = rutaArchivo & "\" & "NombreArchivo.pdf"  ' Reemplaza "NombreArchivo" con el nombre que desees
        
        ' Imprimir el libro de trabajo como PDF en la ubicación especificada
        ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=rutaPDF, Quality:=xlQualityStandard
    Else
        MsgBox "No se puede determinar la ruta del archivo del libro de trabajo.", vbExclamation
    End If
End Sub

Function FindPrinter(PrinterName As String) As String
    ' Función para encontrar la impresora según el nombre especificado
    Dim obj As Object
    For Each obj In Printers
        If obj.Name = PrinterName Then
            FindPrinter = obj.DeviceName
            Exit Function
        End If
    Next obj
End Function