📘 Excel逆引き事典

【VBA】CSVファイルをエラー処理付きでPDF保存する方法

手作業でのCSVファイルのPDF化は労力がかかるだけでなく、ミスの可能性も高まります。この記事では、VBAを使用してCSVファイルを読み込み、エラー処理付きでPDFへ変換・保存する方法を紹介します。

サンプルコード

VBA
Option Explicit
Sub CSVToPDFFromExcel()
    Dim ws As Worksheet
    Dim lastRow As Long, i As Long
    Dim csvFilePath As String
    
    'CSVファイルのパス指定
    csvFilePath = "C:\path\to\yourfile.csv"
    
    On Error GoTo ErrorHandler
    Application.ScreenUpdating = False
    Set ws = ThisWorkbook.Sheets.Add
    With ws.QueryTables.Add(Connection:="TEXT;" & csvFilePath, Destination:=ws.Range("A1"))
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .BackgroundQuery = True
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .WebSelectionType = xlEntirePage
        .WebFormatting = xlWebFormattingNone
        .WebPreFormattedTextToColumns = True
        .WebConsecutiveDelimitersAsOne = True
        .WebSingleBlockTextLoop = False
        .WebDisableDateRecognition = False
        .WebDisableRedirections = False
        .Refresh BackgroundQuery:=False
    End With
    
    'CSVファイルを読み込んだシートの名前を変更
    ws.Name = "ImportedData"
    
    'PDF保存処理
    lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
    For i = 1 To lastRow
        ws.PageSetup.PrintArea = "$A$1:$Z$" & lastRow
        ws.ExportAsFixedFormat Type:=xlTypePDF, Filename:="C:\path\to\output.pdf", Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
    Next i
    
CleanExit:
    Application.ScreenUpdating = True
    Exit Sub
ErrorHandler:
    MsgBox "エラーが発生しました: " & Err.Description
    Resume CleanExit
End Sub

よくある質問

Q 元に戻せますか?

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

Q エラーが出たら?

A.
シート名や列番号が正しいか確認してください。