VBA Search in Outlook

后端 未结 2 1515
自闭症患者
自闭症患者 2020-12-03 02:16

I have this code to search in my folder. I do have a e-mail with the \"sketch\" subject, but VBA is not finding it (it goes to the ELSE clause)

Can anybody tell wha

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-03 02:36

    The reason your .Find isn't working is because Items.Find doesn't support the use of wildcards. Items.Find also doesn't support searching partial strings. So to actually find the email, you'd need to remove the wildcards and include the entire string in your search criteria.

    So here are your options:

    If you know the full subject line you're looking for, modify your code like so:

    Set Mail = olItms.Find("[Subject] = ""This Sketch Email""")
    

    If you don't (or won't) know the full subject, you can loop through your inbox folder and search for a partial subject line like so:

    Untested

    Sub Search_Inbox()
    
    Dim myOlApp As New Outlook.Application
    Dim myNameSpace As Outlook.NameSpace
    Dim myInbox As Outlook.MAPIFolder
    Dim myitems As Outlook.Items
    Dim myitem As Object
    Dim Found As Boolean
    
    Set myNameSpace = myOlApp.GetNamespace("MAPI")
    Set myInbox = myNameSpace.GetDefaultFolder(olFolderInbox)
    Set myitems = myInbox.Items
    Found = False
    
    For Each myitem In myitems
        If myitem.Class = olMail Then
            If InStr(1, myitem.Subject, "sketch") > 0 Then
                Debug.Print "Found"
                Found = True
            End If
        End If
    Next myitem
    
    'If the subject isn't found:
    If Not Found Then
        NoResults.Show
    End If
    
    myOlApp.Quit
    Set myOlApp = Nothing
    
    End Sub
    

    Hope that helps!

提交回复
热议问题