CodexBloom - Programming Q&A Platform

Excel VBA: Automate Saving Specific Sheets as Separate PDF Files Based on Sheet Name

πŸ‘€ Views: 283 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-12
excel vba pdf automation

I'm migrating some code and I'm attempting to set up I tried several approaches but none seem to work. I'm trying to automate the process of saving multiple sheets from an Excel workbook as separate PDF files based on their sheet names using VBA. I've written a macro that iterates through all sheets, but I'm working with an scenario where only the active sheet gets saved as a PDF, regardless of the loop. Here’s the code I have so far: ```vba Sub SaveSheetsAsPDF() Dim ws As Worksheet Dim pdfName As String Dim outputFolder As String outputFolder = "C:\Users\YourUsername\Documents\PDFs\" ' Change to your output path For Each ws In ThisWorkbook.Sheets If ws.Visible = xlSheetVisible Then pdfName = outputFolder & ws.Name & ".pdf" ws.ExportAsFixedFormat Type:=xlTypePDF, Filename:=pdfName, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False End If Next ws End Sub ``` I've ensured that the output folder exists, and the macro runs without any errors, but only the first sheet saves as a PDF, and the others are ignored silently. I've also tried adding debug print statements to confirm that the loop is iterating through all sheets, but they all appear to be processed correctly. What could be causing this behavior? Any insights on how to ensure each sheet is saved separately as intended? I am using Excel 365, and I’ve also checked the permissions for the output folder. Thanks for any help! This is part of a larger CLI tool I'm building. Any advice would be much appreciated. For context: I'm using Vba on Ubuntu 22.04. What are your experiences with this?