📘 Excel逆引き事典

【VBA】特定のフォルダ内の全Excelファイルを高速にPDF保存する方法

手作業での大量のExcelファイルのPDF変換は時間がかかり、ミスも起こりやすいです。この記事では、特定のフォルダ内の全てのExcelファイルを高速にPDF形式で保存する方法を紹介します。

サンプルコード

VBA
Option Explicit
Sub SaveAllFilesAsPDF()
    Dim fso As Object, folder As Object, file As Object
    Dim wb As Workbook, ws As Worksheet
    Dim filePath As String, fileName As String, pdfPath As String
    
    ' フォルダパスを指定
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set folder = fso.GetFolder("C:\\Users\\User\\Documents\\ExcelFiles")
    
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    
    ' フォルダ内の全てのファイルを処理
    For Each file In folder.Files
        If Right(file.Name, 4) = ".xls" Or Right(file.Name, 5) = ".xlsx" Then
            filePath = file.Path
            fileName = fso.GetBaseName(filePath)
            pdfPath = "C:\\Users\\User\\Documents\\PDFFiles\\" & fileName & ".pdf"
            
            ' Excelファイルを開く
            Set wb = Workbooks.Open(filePath)
            wb.ExportAsFixedFormat Type:=xlTypePDF, Filename:=pdfPath
            wb.Close SaveChanges:=False
        End If
    Next file
    
    Application.ScreenUpdating = True
    Application.DisplayAlerts = True
End Sub

よくある質問

Q 元に戻せますか?

A.
VBAの実行結果は「元に戻す」が効きません。必ずバックアップを取ってから実行してください。

Q エラーが出たら?

A.
フォルダパスやファイル名、拡張子が正しいか確認してください。