Vba Print To Pdf And Save - Excel

Sub ExportInvoiceToPDF() Dim ws As Worksheet Dim invoiceNum As String Dim customerName As String Dim filePath As String Set ws = ThisWorkbook.Sheets("Invoice")

'Get values from cells invoiceNum = ws.Range("B5").Value customerName = ws.Range("B6").Value customerName = Replace(customerName, " ", "_") 'Remove spaces

Dim timeStamp As String timeStamp = Format(Now, "yyyymmdd_hhnnss") filePath = "C:\Reports\Report_" & timeStamp & ".pdf" Avoid creating empty PDFs: excel vba print to pdf and save

'Check if folder exists; if not, create it If Dir(folderPath, vbDirectory) = "" Then MkDir folderPath End If

Sub ExportSingleSheetToPDF() Dim ws As Worksheet Dim filePath As String Set ws = ActiveSheet filePath = "C:\PDF Reports\" & ws.Name & ".pdf" Sub ExportInvoiceToPDF() Dim ws As Worksheet Dim invoiceNum

Sub ExportEntireWorkbookToPDF() Dim filePath As String filePath = "C:\PDF Reports\FullWorkbook.pdf"

MsgBox "All sheets saved as PDFs in " & folderPath End Sub To combine all sheets into one PDF file (like a complete annual report): create it If Dir(folderPath

ThisWorkbook.ExportAsFixedFormat Type:=xlTypePDF, _ Filename:=filePath, _ Quality:=xlQualityStandard, _ OpenAfterPublish:=True End Sub 1. Avoid the "File Already Exists" Error If you run the macro twice with the same name, Excel will ask to overwrite. To suppress the prompt and auto-overwrite:

'Loop through each worksheet For Each ws In ThisWorkbook.Worksheets ws.ExportAsFixedFormat Type:=xlTypePDF, _ Filename:=folderPath & ws.Name & ".pdf", _ Quality:=xlQualityStandard Next ws