Search for mail in Sent Items, by date and subject with wildcard, from Excel

江枫思渺然 提交于 2019-12-11 07:11:26

问题


I need to search for mail in Sent Items, sent on current date and with subject as "Task Completed". Sometimes Subject may have additional text like Task Completed on 07/01/2017 or Task Completed 01/09/2017.

I found this Outlook VBA code, which displays found mail. I want the code to run in Excel with wildcard search options and open an Excel file.

I tried to search the subject with wildcard "*", like "Task Completed*" and "Task Completed on & Format(Date, "dd/mm/yyyy")" for which I got an syntax error/compile error

Sub Test()

Dim olApp As Outlook.Application
Dim olNs As NameSpace
Dim Fldr As MAPIFolder
Dim olMail As Outlook.MailItem
Dim i As Integer

Set olApp = New Outlook.Application
Set olNs = olApp.GetNamespace("MAPI")
Set Fldr = olNs.GetDefaultFolder(olFolderSentMail)
i = 1

For Each olMail In Fldr.Items
    If InStr(olMail.Subject, "Task Completed on 07/01/2017") <> 0 Then
        olMail.Display
        i = i + 1    
    End If    
Next olMail

End Sub

I am using Office 2010.


回答1:


In order to loop through all items in Sent Items folder, including Calendar events you may have, use the Dim olMail As Object (instead of AS Outlook.MailItem).

To look for "Task Completed" string somewhere in the email's title, use If olMail.Subject Like "*Task Completed*" Then (adding the wildcard * before and after the searched string).

I've added 2 lines of code, that output all matching emails to your worksheet in Column A and Column B.

Code

Option Explicit

Sub Test()

Dim olApp As Outlook.Application
Dim olNs As Namespace
Dim Fldr As MAPIFolder
Dim olMail As Object
Dim i As Integer, j As Integer

Set olApp = New Outlook.Application
Set olNs = olApp.GetNamespace("MAPI")
Set Fldr = olNs.GetDefaultFolder(olFolderSentMail)

i = 1
For Each olMail In Fldr.Items
    ' check if mail subject contains "Task Completed" in the email title
    If olMail.Subject Like "*Task Completed*" Then
        'Range("A" & i).Value = olMail.Subject ' <-- output email name to column A
        'Range("B" & i).Value = olMail.SentOn ' <-- output email sent date to column B
        olMail.Display ' show email through Excel
        i = i + 1
    End If
Next olMail

End Sub


来源:https://stackoverflow.com/questions/41564816/search-for-mail-in-sent-items-by-date-and-subject-with-wildcard-from-excel

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