LoginSignup
0
0

More than 1 year has passed since last update.

Excel VBAでOutlookの未読メールのみ処理をするテンプレート

Last updated at Posted at 2022-10-19

はじめに

タイトル通りの記事です。
検索するとGetDefaultFolderが多かったのですが、それ以外のフォルダで処理したい人に向けて記事にしました。
ついでに、未読メールのみ、新着順で処理するようにしてあります。

ソースコード

template.vba
Sub test()
    Dim OutLookObject As New Outlook.Application
    Dim myNamespace As Outlook.Namespace
    Dim myFolder As Folder
    Dim n As Integer
    Dim oItem As Object
    Dim objItems As Items

    Set myNamespace = OutLookObject.GetNamespace("MAPI")
    Set myFolder = myNamespace.Folders("user@template.jp").Folders.Item("受信トレイ")
    Set objItems = myFolder.Items
    objItems.Sort "[受信日時]", True    '新着順でソート
    
    n = 0   '処理件数
    
    For Each oItem In objItems
        If oItem.UnRead = True Then
            oItem.UnRead = False
            n = n + 1   '処理件数をカウントアップ
            'メールの処理
            With oItem
                Debug.Print .ReceivedTime & ":" & .SenderName & ":" & .Subject
            End With
            '終了判定
            If myFolder.UnReadItemCount = n Then
                MsgBox "終わり"
                Exit For
            End If
        End If
    Next oItem
    
End Sub

UnreadItemCountについて

Folder.UnreadプロパティをFalseにすることでUnreadItemCountも変化すると思ったのですが、どうやらそうではなかったようです。苦肉の策、と言うほどではないのですが、処理件数用の変数を用意して、すべての未読メールを処理したタイミングで処理を抜けるようにしておきました。

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