LoginSignup
12
17

More than 5 years have passed since last update.

EXCELのVBAマクロでOutlookメールを作成する方法

Last updated at Posted at 2014-12-17

決められたフォーマットでOutlookメールを自動生成したい場合に参考にしてください。

Option Explicit

'#########################################
'
' 関数名:MakeMail
' パラメータ:
'   toAddress(String):宛先アドレス
'   ccAddress(String):CCアドレス
'   bccAddress(String):BCCアドレス
'   subject(String):件名
'   mailBody(String):本文
'   credit(String):メール末尾の署名文
'   replaceList(Object[Scripting.Dictionary]):件名と本文の置換リスト
' 説明:
'   入力パラメータを基にOutlookメールを作成する。
' 備考:
'   replaceListはディクショナリで{<%start_date%>, '20141217'}のような
'   データが入るイメージ
'
'#########################################
Sub MakeMail(toAddress As String, _
             ccAddress As String, _
             bccAddress As String, _
             subject As String, _
             mailBody As String, _
             credit As String, _
             replaceList As Object)

    On Error GoTo ErrHandler

    'メール作成に必要なOutlookオブジェクトを生成する
    Dim outlookObj As Outlook.Application
    Dim mailItemObj As Outlook.MailItem
    Set outlookObj = CreateObject("Outlook.Application")
    Set mailItemObj = outlookObj.CreateItem(olMailItem)

    'メール情報の設定
    mailItemObj.To = toAddress
    mailItemObj.CC = ccAddress
    mailItemObj.BCC = bccAddress
    mailItemObj.subject = subject

    Dim tmpSubject As String
    tmpSubject = subject

    Dim tmpMailBody As String
    tmpMailBody = mailBody & credit

    Dim key As Variant
    Dim value As Variant

    '件名を置換する
    For Each key In replaceList
        value = replaceList.Item(key)
        tmpSubject = Replace(tmpSubject, key, value)
    Next key

    'メール本文を置換する
    For Each key In replaceList
        value = replaceList.Item(key)
        tmpMailBody = Replace(tmpMailBody, key, value)
    Next key

    mailItemObj.subject = tmpSubject
    mailItemObj.Body = tmpMailBody

    '下書き保存(保存したければコメントを外す)
    'mailItemObj.Save
    'メール表示
    mailItemObj.Display

    'オブジェクトの解放
    Set mailItemObj = Nothing
    Set outlookObj = Nothing

    Exit Sub

' 例外処理
ErrHandler:

    Set mailItemObj = Nothing
    Set outlookObj = Nothing

    MsgBox "メール作成時に例外発生"

End Sub

以上

12
17
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
17