guialmachado
guialmachado

Reputation: 546

Download outlook attachment with subject

I got this VBA code and edited it to download attachment from an email by its subject, but it doesnt recognize any subject.

I want to run it with Excel

Can anyone point where is the mistake?

Const olFolderInbox As Integer = 6
'~~> Path for the attachment
Const AttachmentPath As String = "C:\"

Sub DownloadAttachmentFirstUnreadEmail()
    Dim oOlAp As Object, oOlns As Object, oOlInb As Object
    Dim oOlItm As Object, oOlAtch As Object

    '~~> New File Name for the attachment
    Dim NewFileName As String
    NewFileName = AttachmentPath

    '~~> Get Outlook instance
    Set oOlAp = GetObject(, "Outlook.application")
    Set oOlns = oOlAp.GetNamespace("MAPI")
    Set oOlInb = oOlns.GetDefaultFolder(olFolderInbox)

    '~~> Check if there are any actual unread emails
    If oOlInb.Items.Restrict("[Subject] =" & "Sample Subject").Count = 0 Then
        MsgBox "NO Email In Inbox with [Subject] = Sample Subject"
    End If

    '~~> Extract the attachment from the 1st unread email
    For Each oOlItm In oOlInb.Items.Restrict("[Subject] =" & "Sample Subject")
        '~~> Check if the email actually has an attachment
        If oOlItm.Attachments.Count <> 0 Then
            For Each oOlAtch In oOlItm.Attachments
                '~~> Download the attachment
                oOlAtch.SaveAsFile NewFileName & oOlAtch.Filename
                Exit For
            Next
        Else
            MsgBox "The First item doesn't have an attachment"
        End If
        Exit For
    Next
 End Sub

Upvotes: 0

Views: 182

Answers (1)

Tim Williams
Tim Williams

Reputation: 166885

Try

oOlInb.Items.Restrict("[Subject] ='" & "Sample Subject" & "'") 

You need quotes around string values

Upvotes: 1

Related Questions