How to filter an Outlook view in VBA based on “To” email addresses

白昼怎懂夜的黑 提交于 2021-01-18 06:41:44

问题


I have a view in Outlook that includes both "From" and "To" emails from a mailbox

I can very easily type in an email address into the Outlook search box, and the view will be instantly filtered to show all emails to and from the email address (plus perhaps, any other emails including this email address in the subject or body, but that's not an issue)

I would like to replicate this process via VBA - I have an Access DB with contact details, and would like to be able to simply filter this view based on a contact email address in the DB.

It seems like a very simple problem, but I can't find the solution. I have code that eg filters based on the from email address, but there seems no way to filter on a 'To' email address (I can filter on the 'To' display name but this is next to useless - it varies from one email to another, and seldom if ever contains the actual email address)

I have a DASL filter code that works to filter on the 'From' email addresses using DASL syntax as follows:

Const SchemaFrom As String = "urn:schemas:httpmail:fromemail"
Dim EM as string
EM = "myemail@me.com"
objView.Filter = Chr(34) & SchemaFrom & Chr(34) & " = '" & EM & "'"

But there is nothing similar for 'To' emails.

Ultimately I don't even need to filter based on eg the 'From' and 'To' email addresses - if there is a way to code this, so, like in the search box, it simply filters on any text field containing the email address that would be fine by me!!!

For example, is there a generic DASL search that will do this, so no need to eg dictate searching in eg fromemail?

All help much appreciated - it is so simple to do in the GUI of Outlook it must be possible from VBA surely?!


回答1:


Should be

Dim Filter As String
    Filter = "@SQL=" & Chr(34) & "urn:schemas:httpmail:fromemail" & _
                       Chr(34) & " Like '%0m3r 0m3r%'"

Or use

Filter = "[SenderEmailAddress] = '0m3r@email.com'"

Example

Option Explicit
Private Sub Examples()
    Dim olNs As Outlook.NameSpace
    Dim Inbox As Outlook.MAPIFolder
    Dim Item As Outlook.MailItem
    Dim Items As Outlook.Items
    Dim msg As String

    Set olNs = Application.GetNamespace("MAPI")
    Set Inbox = olNs.GetDefaultFolder(olFolderInbox)

    Dim Filter As String
        Filter = "@SQL=" & Chr(34) & "urn:schemas:httpmail:fromemail" & _
                           Chr(34) & " Like '%0m3r 0m3r%'"

    Set Items = Inbox.Items.Restrict(Filter)

    msg = Items.Count & " Items in " & Inbox.Name

    MsgBox (msg)

End Sub

MSDN fromemail Field | Microsoft Docs

https://stackoverflow.com/search?tab=votes&q=user%3a4539709%20%5boutlook-filter%5d



来源:https://stackoverflow.com/questions/55924883/how-to-filter-an-outlook-view-in-vba-based-on-to-email-addresses

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!