ORLANDO VAZQUEZ
ORLANDO VAZQUEZ

Reputation: 79

How to extract email attachment from Outlook mail items received today?

The code below is simple and works however, it needs to be modified so that when it looks in the outlook folder it only looks at mail items with a received date = today. I've spent hours trying to fix this.

Sub Command0_Click()
    Dim OlApp As Object
    Dim OlMail As Object
    Dim OlItems As Object
    Dim OlFolder As Object
    Dim J As Integer
    Dim strFolder As String
    Dim CurrentDate As String
    CurrentDate = Format(Now, "YYYYMMDD") '
    Dim aFile As String

    On Error Resume Next
    Set OlApp = GetObject(, "Outlook.Application")

    If Err.Number = 429 Then
        Set OlApp = CreateObject("Outlook.Application")
    End If

    strFolder = "H:\TEST_DROP\" ' Folder where saving attachments

    '''Outlook folder path
    'Change Folder to your email adddress
    'Change inbox to your subfolder in the your main mailbox
    Set OlFolder = OlApp.getnamespace("MAPI").Folders("MyEmail@my_company.com").Folders("Inbox").Folders("TEST_ML")

    Set OlItems = OlFolder.Items

    ''looks in each email in that folder and saves attachments in strFolder
    '''THE CODE HERE NEEDS TO BE MODIFIED TO ONLY LOOK AT THE EMAILS WITH A RECEIVED DATE OF TODAY only....
    For Each OlMail In OlItems
        If OlMail.Attachments.Count > 0 Then
            For J = 1 To OlMail.Attachments.Count
                OlMail.Attachments.Item(J).SaveAsFile strFolder & OlMail.Attachments.Item(J).FileName
            Next J
        End If
    Next

    Set OlFolder = Nothing
    Set OlItems = Nothing
    Set OlMail = Nothing
    Set OlApp = Nothing

    ''''RENAME FILE WITH CURRENT DATE SUFFIX
    Name "H:\TEST_DROP\Remittance_YYYYMMDD.csv" As "H:\TEST_DROP\Remittance_" & CurrentDate & ".csv"

End Sub

Upvotes: 0

Views: 392

Answers (1)

HackSlash
HackSlash

Reputation: 5812

Each mail item has a property OlMail.ReceivedTime

You need to compare that to Now()

Like this:

If (Now() - OlMail.ReceivedTime) < 1 Then

This works because the result of this evaluation is the number of days between the two. Time is a fraction of a day.

Upvotes: 1

Related Questions