Check for the senderEmailAddress

2019-01-20 05:19发布

I have a listener in VBA on my outlook box to perform an action if a receive a mail from a specific email.

The problem is that if I get a error mail (non-delivery email) then my condition is run on a mail which doesn't have that property so my method crashes.

I don't know what the subject may be either.

Does anyone have an idea if I can test if the property exists or if there is another property I can check for to identify if my sender matches?

Many thanks in advance

Sub SetFlagIcon() 

 Dim mpfInbox As Outlook.Folder 

 Dim obj As Outlook.MailItem 

 Dim i As Integer 



 Set mpfInbox = Application.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox).Folders("Test") 

 ' Loop all items in the Inbox\Test Folder 

 For i = 1 To mpfInbox.Items.Count 

 If mpfInbox.Items(i).Class = olMail Then 

 Set obj = mpfInbox.Items.Item(i) 

 If obj.SenderEmailAddress = "someone@example.com" Then 

 'Set the yellow flag icon 

 obj.FlagIcon = olYellowFlagIcon 

 obj.Save 

 End If 

 End If 

 Next 

End Sub

1条回答
Anthone
2楼-- · 2019-01-20 05:58

Dim obj as a generic Object - there are objects other than MailItem in your Inbox, also to improve your loop try using Items.Restrict Method (Outlook)

Option Explicit
Sub SetFlagIcon()
    Dim mpfInbox As Outlook.Folder
    Dim obj As Object
    Dim Items As Outlook.Items
    Dim i As Long
    Dim Filter As String

    Set mpfInbox = Application.GetNamespace("MAPI").GetDefaultFolder _
                                    (olFolderInbox).Folders("Temp")

    Filter = "[SenderEmailAddress] = 'someone@example.com'"

    Set Items = mpfInbox.Items.Restrict(Filter)

    ' Loop all items in the Inbox\Test Folder
    For i = 1 To Items.Count
        If Items(i).Class = olMail Then
            Set obj = Items(i)
            'Set the yellow flag icon
            obj.FlagIcon = olYellowFlagIcon
            obj.Save
        End If
    Next

End Sub

Items.Restrict Method Applies a filter to the Items collection, returning a new collection containing all of the items from the original that match the filter.

查看更多
登录 后发表回答