0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Outlook VBA】差出人・件名が空白のメールを自動削除するマクロ

Posted at

【Outlook VBA】差出人・件名が空白のメールを自動削除するマクロ

Outlookを利用していて「差出人」や「件名」が空白の迷惑メールが届くことはありませんか?
標準の仕分けルールでは対応が難しいため、VBAマクロで自動処理する方法を紹介します。


完成コード(ThisOutlookSession に貼り付け)

Option Explicit

' --- 設定項目 ---
' True = 件名か差出人が空白なら削除(リスク高)
' False = 件名と差出人が両方空白の場合のみ削除(安全・推奨)
Const DELETE_IF_EITHER_IS_BLANK As Boolean = False

' 移動先フォルダ: 3=削除済みアイテム, 23=迷惑メール
Const TARGET_FOLDER As Integer = 3
' --- 設定ここまで ---

Private Sub Application_NewMailEx(ByVal EntryIDCollection As String)
    Const olMail As Integer = 43
    Dim arrEntryIDs As Variant, objMail As Object
    Dim ns As Outlook.NameSpace, targetFolderObject As Outlook.MAPIFolder
    Dim subjectIsEmpty As Boolean, senderIsEmpty As Boolean, deleteThisMail As Boolean
    Dim i As Long

    Set ns = Application.GetNamespace("MAPI")
    Set targetFolderObject = ns.GetDefaultFolder(TARGET_FOLDER)
    arrEntryIDs = Split(EntryIDCollection, ",")

    For i = LBound(arrEntryIDs) To UBound(arrEntryIDs)
        Set objMail = ns.GetItemFromID(arrEntryIDs(i))
        If Not objMail Is Nothing Then
            If objMail.Class = olMail Then
                subjectIsEmpty = (Trim(objMail.Subject) = "")
                senderIsEmpty = (Trim(objMail.SenderName) = "")
                deleteThisMail = False

                If DELETE_IF_EITHER_IS_BLANK Then
                    If subjectIsEmpty Or senderIsEmpty Then deleteThisMail = True
                Else
                    If subjectIsEmpty And senderIsEmpty Then deleteThisMail = True
                End If

                If deleteThisMail Then objMail.Move targetFolderObject
            End If
        End If
    Next i
End Sub

設定方法

  1. Outlookのリボンに「開発」タブを表示する
    • [ファイル] → [オプション] → [リボンのカスタマイズ] で「開発」にチェックを入れる
  2. [開発] タブ → Visual Basic をクリック
  3. 左側で ThisOutlookSession をダブルクリック
  4. 上記コードを貼り付けて保存
  5. Outlookを再起動

動作確認

  • 件名・差出人が空白のテストメールを送信すると、自動で「削除済みアイテム」に移動します
  • Const TARGET_FOLDER As Integer = 23 に変更すると「迷惑メール」フォルダへ移動可能です

注意点

  • 初期値 True(OR条件)は誤削除リスク大
    • 基本は False(AND条件)を推奨
  • 自動移動されたメールは復元できない場合があります
    • まずは「迷惑メールフォルダ」振り分けでテスト運用をおすすめ
  • Mac版Outlook・Web版・スマホアプリは VBA非対応

まとめ

  • Outlook標準ルールでは難しい「差出人・件名が空白メールの自動削除」をVBAで実現可能
  • 誤削除防止のため、AND条件 × 迷惑メールフォルダ での運用が安全
  • 新着メールを即チェックして不要なものを自動移動できます

参考リンク

より詳しい手順や画面キャプチャ付きの解説は、以下の記事で紹介しています。

Outlook VBA:差出人や件名が空白のメールを自動的に削除する方法|情シスの自由帳

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?