エクセルのシートをPDF化して、Outlookに添付するVBAを紹介します。

エクセルファイルをそのままメールに添付できない時は多いですよね。



そうですね。
請求書、領収書、発注書などはエクセルで計算させると便利ですが、
エクセルだと受け取った人も修正ができちゃいますよね。



今回は、PDF化したエクセルのシートをOutlookに添付します。


エクセルをPDF化してメールに添付する(outlook)VBA
エクセルをPDF化してメールに添付する(outlook)VBA
マクロが設定されているファイル名が「BOOK1.xlsm」の場合、次のようなメールが作成される。


Sub SendWorkSheetToPDF()
Dim Wb As Workbook
Dim FileName, MailA, TextA As String
Dim OutlookApp As Object
Dim OutlookMail As Object
Set Wb = Application.ActiveWorkbook
MailA = “——@aaaaaa.co.jp”
TextM = “Hello”
FileName = Wb.FullName
xIndex = VBA.InStrRev(FileName, “.”)
If xIndex > 1 Then FileName = VBA.Left(FileName, xIndex – 1)
FileName = FileName & “.pdf”
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, FileName:=FileName
Set OutlookApp = CreateObject(“Outlook.Application”)
Set OutlookMail = OutlookApp.CreateItem(0)
With OutlookMail
.To = MailA
.CC = “”
.BCC = “”
.Subject = “こんにちは”
.Body = TextM
.Attachments.Add FileName
.Display
End With
Kill FileName
Set OutlookMail = Nothing
Set OutlookApp = Nothing
End Sub


解説
応用編
複数の宛先に、それぞれの内容に併せたファイルを添付したい場合
- シートを作成する


- 「一覧」シートに宛先とメールアドレスを記入する


- 宛先ごとのシートに内容を作成する


VBA
Sub SendWorkSheetToPDF()
Dim a As Long
Dim Wb As Workbook
Dim FileName, Company, MailA, TextA As String
Dim OutlookApp As Object
Dim OutlookMail As Object
On Error Resume Next
Set Wb = Application.ActiveWorkbook
a = Sheets(1).Cells(Rows.Count, 1).End(xlUp).Row
For i = 2 To a
Sheets(i).Select
Company = Sheets(1).Cells(i, 1)
MailA = Sheets(1).Cells(i, 2)
TextM = “添付ファイル参照”
FileName = Wb.FullName
xIndex = VBA.InStrRev(FileName, “.”)
If xIndex > 1 Then FileName = VBA.Left(FileName, xIndex – 1)
FileName = FileName & “_” & Company & “様.pdf”
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, FileName:=FileName
Set OutlookApp = CreateObject(“Outlook.Application”)
Set OutlookMail = OutlookApp.CreateItem(0)
With OutlookMail
.To = MailA
.CC = “”
.BCC = “”
.Subject = “お支払額のご連絡”
.Body = Company & “ 様” & vbCrLf & vbCrLf & TextM
.Attachments.Add FileName
.Display
End With
Kill FileName
Set OutlookMail = Nothing
Set OutlookApp = Nothing
Next i
Sheets(1).Select
End Sub
解説
エラーの場合は次に進む
左から1番目のシート「一覧」・A列の最終行を取得する
2~aまでにおいて(ループ)
添付するシートを選択する
宛先の取得
メールアドレスの取得
本文の取得
添付ファイルのファイル名を作成
→ファイル名_宛先様.pdf
Outlookの設定
メールアドレス
CC
BCC
メールタイトル
本文:「宛先」様 <改行><改行> 本文
添付ファイルを作成
プレビュー ※直接送りたい場合は「Send」
それぞれを空にする
結果





エクセルをPDF化してメールに添付するVBAでした。


コメント