Click here to Skip to main content
15,887,214 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
So I have made this macro in excel that checks outlook inbox and downloads attachments from mails coming from certain user. For now, I run the macro manually at a specific time. But I want the macro to get fired when that particular mail enters the mailbox. I mostly work with excel macros and want it to operate from excel side only as much as possible. Moreover, the mailbox will be someone else's so I do not want to do much there.

What I have tried:

Public Sub db_upload()

    'download file from outlook
    Dim ns As Outlook.Namespace
    Dim inbox As Outlook.MAPIFolder
    Dim mail As Object
    Dim attachmnt As Outlook.Attachment
    Dim fname As String
    Dim docPath As String
    Dim i As Integer
    Dim wsh As Object
    Dim fs As Object
    cnt = 0

    Set ns = GetNamespace("MAPI")
    Set inbox = ns.GetDefaultFolder(olFolderInbox)
    maildt = Format(Now, "dd-mm-yyyy")

    For Each mail In inbox.Items
        On Error Resume Next
        namesender = mail.SenderName
        mailsub = mail.Subject
        maildate = Format(mail.ReceivedTime, "dd-mm-yyyy")

        If InStr(mail.Subject, "something") > 0 And Format(mail.ReceivedTime, "dd-mm-yyyy") = maildt Then
            For Each attachmnt In mail.Attachments
                fname = attachmnt.Filename
                attachmnt.SaveAsFile "path" & attachmnt.Filename
                cnt = cnt + 1
            Next attachmnt
        End If
    Next mail

    Set inbox = Nothing
    Set ns = Nothing
    Set fs = Nothing
    Set wsh = Nothing
End Sub
Posted
Updated 10-Apr-17 10:10am
v2
Comments
Richard MacCutchan 10-Apr-17 9:05am    
You need something in the mail client to signal when a message is received.

1 solution

You can't do that from Excel side only. As Richard MacCutchan mentioned in the comment to the question, you have to catch Outtlok's event when new email incomming.
I'd suggest to read this: How to process incoming messages in Microsoft Outlook[^] - method 3. The same you'll find here: Processing Incoming E-mails with Macros[^]

For further details, please see: Outlook VBA reference[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900