【VBA】特定の名前のシートをエラー処理付きでPDF保存する方法
手作業でのPDF出力は時間がかかります。この記事では、特定の名前のシートを自動的にPDFに変換し、エラー処理も含めて効率化します。
サンプルコード
VBA
Option Explicit
Sub SaveSheetAsPdf()
Dim ws As Worksheet
Dim pdfPath As String
On Error GoTo ErrorHandler
Set ws = ThisWorkbook.Sheets("特定のシート名")
If ws Is Nothing Then
MsgBox "指定したシートが存在しません。", vbExclamation
Exit Sub
End If
Application.ScreenUpdating = False
pdfPath = Environ("USERPROFILE") & "\Desktop\" & ws.Name & ".pdf"
ws.ExportAsFixedFormat Type:=xlTypePDF, Filename:=pdfPath, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
Application.ScreenUpdating = True
MsgBox "PDFファイルが作成されました。", vbInformation
Exit Sub
ErrorHandler:
MsgBox Err.Description, vbCritical
End Subよくある質問
Q 元に戻せますか?
A.
VBAの実行結果は「元に戻す」が効きません。必ずバックアップを取ってから実行してください。
Q エラーが出たら?
A.
シート名や列番号が正しいか確認してください。