VBA for PDF: Automate PDF Creation, Editing & Extraction

VBA code for PDF

Export as PDF file and Auto Save

 Sub ExportAsPDFAutoSave()
    Dim FileName As String    

    ' Auto-generate PDF file name with timestamp
    FileName = ThisWorkbook.Path & "\" & _
                  "Report_" & Format(Now, "yyyymmdd_hhmmss") & ".pdf"    

    ' Export the active sheet directly as PDF (auto-saved)
    ActiveSheet.ExportAsFixedFormat _
        Type:=xlTypePDF, _
        FileName:=FileName, _
        Quality:=xlQualityStandard, _
        IncludeDocProperties:=True, _
        IgnorePrintAreas:=False, _
        OpenAfterPublish:=False   

    MsgBox "PDF saved as:" & vbCrLf & newFileName, vbInformation, "Export Complete"

End Sub


Export Excel Sheet to PDF

Sub ExportSheetToPDF()
    Dim FilePath As String
    FilePath = ThisWorkbook.Path & "\MySheet.pdf"
    
    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
        Filename:=FilePath, _
        Quality:=xlQualityStandard, _
        IncludeDocProperties:=True, _
        IgnorePrintAreas:=False, _
        OpenAfterPublish:=True
End Sub


Save Specific Range as PDF

Sub ExportRangeToPDF()
    Dim rng As Range
    Set rng = Range("A1:D20")
    rng.ExportAsFixedFormat _
        Type:=xlTypePDF, _
        Filename:=ThisWorkbook.Path & "\RangeExport.pdf"
End Sub


Export Multiple Sheets as One PDF

Sub ExportMultipleSheetsToPDF()
    Sheets(Array("Sheet1", "Sheet2")).Select
    ActiveSheet.ExportAsFixedFormat _
        Type:=xlTypePDF, _
        Filename:=ThisWorkbook.Path & "\MultiSheets.pdf"
End Sub


Convert Word Document to PDF (From Word)

Sub SaveAsPDF()
    Dim FilePath As String
    FilePath = ActiveDocument.Path & "\" & _
               Replace(ActiveDocument.Name, ".docx", ".pdf")
    ActiveDocument.ExportAsFixedFormat _
        OutputFileName:=FilePath, _
        ExportFormat:=wdExportFormatPDF
End Sub


Attach Generated PDF to Outlook Email

Sub ExportToPDF_AttachEmail()
    Dim FilePath As String
    FilePath = ThisWorkbook.Path & "\Report.pdf"
    ActiveSheet.ExportAsFixedFormat _
        Type:=xlTypePDF, Filename:=FilePath
    Dim OutApp As Object, OutMail As Object
    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)
    With OutMail
        .To = "example@mail.com"
        .Subject = "PDF Report"
        .Body = "Please find attached the report."
        .Attachments.Add FilePath
        .Display 'use .Send to auto-send
    End With
End Sub


Print PDF Automatically (Using Shell)

Sub PrintPDF()
    Dim FilePath As String
    FilePath = "C:\Users\Public\Document.pdf"
    Shell "cmd /c start acrord32.exe /p /h """ & FilePath & """", vbHide
End Sub

एक टिप्पणी भेजें

0 टिप्पणियाँ