Skip to content

Instantly share code, notes, and snippets.

@YujiFukami
Created January 17, 2024 09:40
Show Gist options
  • Save YujiFukami/fd191492db7c2a0f6c8f26a0c044013e to your computer and use it in GitHub Desktop.
Save YujiFukami/fd191492db7c2a0f6c8f26a0c044013e to your computer and use it in GitHub Desktop.
Public Sub OutputPDF(ByRef Sheet As Worksheet, _
ByRef FolderPath As String, _
ByRef FileName As String, _
Optional ByRef Message As Boolean = True)
'指定シートをPDFで出力する
'20210721
'20231102 出力失敗の対策追加
'参考
'https://www.softex-celware.com/post/outputpdf
'引数
'Sheet ・・・PDF化する対象のシート
'FolderPath・・・出力先フォルダパス
'FileName ・・・出力PDFのファイル名
'[Message] ・・・出力確認のメッセージを表示するかどうか
' 省略なら表示する
'処理
'出力するPDFのファイル名を作成する
Dim PDFPath As String
PDFPath = FolderPath & "\" & FileName & ".pdf"
'PDFで出力する
On Error GoTo ErrorEscape1
Sheet.ExportAsFixedFormat Type:=xlTypePDF, FileName:=PDFPath
GoTo ErrorEscape2
ErrorEscape1:
'同じPDFが起動中の場合はエラーになる
MsgBox "PDF出力に失敗しました" & vbLf & _
"同じ名前のPDFが起動中の可能性があります", _
vbExclamation
ErrorEscape2:
'PDFの出力先のフォルダを起動するか確認
Dim MessageStr As String
If Message = True Then
MessageStr = "「" & FileName & ".pdf" & "」" & vbLf & _
"を作成しました" & vbLf & _
"出力先フォルダを起動しますか?"
If MsgBox(MessageStr, vbYesNo + vbInformation) = vbYes Then
Shell "C:\Windows\explorer.exe " & _
FolderPath, vbNormalFocus
End If
End If
End Sub
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment