VBA & Macro Problems

Export the First Worksheet of Multiple Excel Workbooks to PDF

Phi Hung VoPhi Hung Vo Nov 18, 2026 868 views

Question details

Export the first worksheet from approximately 100 Excel workbooks into separate PDF files without the batch stopping prematurely.

Export the First Worksheet of Multiple Excel Workbooks to PDF
Product
Microsoft Excel
Device & OS
not provided
Scenario
A VBA macro opens workbooks in a folder and exports the first worksheet from each one.
Observed behavior
Excel may appear unresponsive or stop processing after a few files.
Before you start

Place the source workbooks in one folder and choose an output folder where you can create PDF files. Close the source workbooks before running the macro, and enable macros only for code and files you trust.

Solution 1Recommended

Run a VBA batch export with unique PDF names and error logging

Use this macro to process each workbook separately, avoid filename collisions, and continue after individual export errors.

The macro first collects the source filenames, then opens each workbook read-only and exports Worksheets(1). It names each PDF after the complete workbook filename and adds a number if that PDF already exists.

DoEvents can help Excel remain responsive, but it cannot correct invalid paths, duplicate filenames, or file-processing errors. A large batch can still take time.

1
Open the VBA editor

In Excel, open a macro-enabled workbook from which to run the export. Press Alt+F11, or use Developer > Visual Basic.

2
Insert the macro

In the VBA editor, choose Insert > Module and paste the following code: Option Explicit Sub ExportFirstWorksheetsToPDF() Dim inputFolder As String, outputFolder As String Dim fileName As String, pdfPath As String, basePath As String Dim files As Collection, item As Variant Dim n As Long, succeeded As Long, failed As Long Dim errorText As String Dim oldEvents As Boolean, oldScreen As Boolean, oldSecurity As Long With Application.FileDialog(msoFileDialogFolderPicker) .Title = "Select the source workbook folder" If .Show <> -1 Then Exit Sub inputFolder = .SelectedItems(1) & Application.PathSeparator .Title = "Select the PDF output folder" If .Show <> -1 Then Exit Sub outputFolder = .SelectedItems(1) & Application.PathSeparator End With oldEvents = Application.EnableEvents oldScreen = Application.ScreenUpdating oldSecurity = Application.AutomationSecurity On Error GoTo BatchError Application.EnableEvents = False Application.ScreenUpdating = False Application.AutomationSecurity = 3 ' Force-disable VBA macros in opened files. Set files = New Collection fileName = Dir$(inputFolder & "*.xls*") Do While fileName <> "" If Left$(fileName, 2) <> "~$" Then If StrComp(inputFolder & fileName, ThisWorkbook.FullName, vbTextCompare) <> 0 Then files.Add fileName End If End If fileName = Dir$() Loop For Each item In files fileName = CStr(item) basePath = outputFolder & fileName pdfPath = basePath & ".pdf" n = 1 Do While Dir$(pdfPath) <> "" pdfPath = basePath & "-" & n & ".pdf" n = n + 1 Loop Debug.Print "Processing: " & fileName errorText = "" If ExportOneWorkbook(inputFolder & fileName, pdfPath, errorText) Then succeeded = succeeded + 1 Else failed = failed + 1 Debug.Print "Failed: " & fileName & " - " & errorText End If DoEvents Next item GoTo CleanUp BatchError: Debug.Print "Batch stopped: " & Err.Description MsgBox "Batch stopped: " & Err.Description, vbExclamation CleanUp: Application.AutomationSecurity = oldSecurity Application.EnableEvents = oldEvents Application.ScreenUpdating = oldScreen MsgBox "Exported: " & succeeded & vbCrLf & "Failed: " & failed & _ vbCrLf & "Check the VBA Immediate window for details.", vbInformation End Sub Private Function ExportOneWorkbook(sourcePath As String, pdfPath As String, _ ByRef errorText As String) As Boolean Dim wb As Workbook On Error GoTo FileError Set wb = Workbooks.Open(Filename:=sourcePath, UpdateLinks:=0, ReadOnly:=True) wb.Worksheets(1).ExportAsFixedFormat Type:=xlTypePDF, Filename:=pdfPath, _ Quality:=xlQualityStandard, IncludeDocProperties:=False, _ IgnorePrintAreas:=False, OpenAfterPublish:=False wb.Close SaveChanges:=False Set wb = Nothing ExportOneWorkbook = True Exit Function FileError: errorText = Err.Description On Error Resume Next If Not wb Is Nothing Then wb.Close SaveChanges:=False On Error GoTo 0 End Function

3
Run the export

Place the cursor inside ExportFirstWorksheetsToPDF and press F5. Select the source folder, then select the PDF output folder.

4
Review the results

Check the completion message and the output folder. In the VBA editor, press Ctrl+G to open the Immediate window and see the current filename and any logged errors.

Run a VBA batch export with unique PDF names and error logging
Check failed workbooks: Password-protected files, inaccessible folders, unusually long paths, or worksheets that cannot be exported may fail. The macro logs those errors and continues with the next collected file.
Free Microsoft Office alternative

Open and export Excel workbooks with WPS Office

WPS Office is a free, lightweight alternative with a familiar spreadsheet interface. Open existing Excel files and export worksheets to PDF; VBA support and batch automation can vary by version and configuration, so check your workflow before migrating.

Export spreadsheet content to PDF from WPS SpreadsheetsCompatible with Microsoft Excel formats such as XLSX and XLSFamiliar interface for working with existing spreadsheetsFree and lightweight for everyday office tasks
microsoft office alternative - wps office

Frequently Asked Questions

Why do some exported PDFs appear to be missing?

If the macro uses only the worksheet name for each PDF, workbooks with identically named first sheets can produce conflicting filenames. Use the workbook filename and check the output folder for numbered copies.

Does DoEvents fix a macro that stops after a few files?

No. DoEvents gives Excel an opportunity to process interface events, but it does not fix invalid paths, filename conflicts, or errors. Check the VBA Immediate window with Ctrl+G for the file and error message.

Will the macro export every worksheet in each workbook?

No. The call to wb.Worksheets(1).ExportAsFixedFormat exports only the first worksheet in each source workbook. Existing print areas are respected because IgnorePrintAreas is False.

What happens if a PDF with the same name already exists?

The sample checks the output folder and adds a number to the new PDF filename rather than deliberately reusing the existing name.

Can I run the same Excel VBA batch macro in WPS Office?

VBA support can vary by WPS Office version and configuration. Check whether your installation supports the required VBA features and test the macro before relying on it for a batch export.