Using Restrict method for emails within a specified date

前端 未结 3 1335
说谎
说谎 2021-01-23 08:40

I am creating a macro to get email by subject and received date in our team shared box. My problem is that once I select date (e,g 1/16/2018 to 1/17/2018), only few emails are s

3条回答
  •  攒了一身酷
    2021-01-23 09:12

    Expounding my comment you can try using below with the following considerations:

    1. Received date, datereceived is expressed in UTC. So you need to adjust your time depending on your UTC. In my case it is UTC8 so I need to adjust the time 8 hours earlier (Note: No documentation to support this, but when I did my testing, it is expressed in UTC.
      It may or may not always be the case
      ).
    2. Date should be expressed as string as stated here.

      Although dates and times are typically stored with a Date format, the Find and Restrict methods require that the date and time be converted to a string representation.

      Example:

      mydate = Format(Now,"\'m/d/yyy hh:mm AM/PM\'") '/* will give '1/23/2018 01:36 PM' */
      
    3. sendername may contain the email address or the email name.

    Sub stancial()
        Dim olItems As Outlook.Items
        Dim olFolder As Outlook.Folder
        Dim olNS As Outlook.NameSpace
        Dim olEmail As Outlook.MailItem
        Dim i As Long
    
        Dim efilter As String, startdt As String, endindt As String, _
            myUTC As Integer, sentby As String
    
        myUTC = 8 '/* this is your UTC, change to suit (in my case 8) */
    
        startdt = Format(DateAdd("h", -myUTC, _
                  CDate("1/18/2018 12:00 PM")), "\'m/d/yyyy hh:mm AM/PM\'")
        endindt = Format(DateAdd("h", -myUTC, _
                  CDate("1/18/2018 4:00 PM")), "\'m/d/yyyy hh:mm AM/PM\'")
        sentby = "'john.doe@email.com'" '/* can be sendername, "doe, john" */
    
        Set olNS = Application.GetNamespace("MAPI")
        Set olFolder = olNS.GetDefaultFolder(olFolderInbox)
        '/* filter in one go, where datereceived is
        'expressed in UTC (Universal Coordinated Time) */
        efilter = "@SQL= (urn:schemas:httpmail:sendername = " & sentby & _
                  " And (urn:schemas:httpmail:datereceived >= " & startdt & _
                  " And urn:schemas:httpmail:datereceived <= " & endindt & "))"
    
        Set olItems = olFolder.Items.Restrict(efilter)
    
        With olItems
            For i = .Count To 1 Step -1 '/* starting from most recent */
                If TypeOf .Item(i) Is MailItem Then
                    Set olEmail = .Item(i)
                    Debug.Print olEmail.Subject, olEmail.ReceivedTime
                End If
            Next
        End With
    End Sub
    

提交回复
热议问题