1

I found VBA code (here) to download attachments from all emails in an Outlook folder.

I would like to download attachments from emails that were received after a certain date. I tried the Restrict method but got the following error:

Run time error 13:
Type mismatch

The Code:

Dim msg As Outlook.MailItem
Dim fo As Outlook.Folder
Dim at As Outlook.Attachment
Dim cell1 As String
Dim sFilter As String

cell1 = Range("O2").Value 'Cell O2 has the following text in it: .xls

Set fo = Outlook.GetNamespace("MAPI").Folders("Winter").Folders("Inbox")
sFilter = "[Inbox.Items] > '" & Format("7/2/19 1:00am", "ddddd h:nn AMPM") & "'"
Set fo = fo.Items.Restrict(sFilter) 

Dim lr As Integer

For Each msg In fo.Items 'Line where debugger points to
    lr = Application.WorksheetFunction.CountA(sh.Range("A:A"))

    sh.Range("A" & lr + 1).Value = msg.Subject
    sh.Range("B" & lr + 1).Value = msg.Attachments.Count

    For Each at In msg.Attachments
       If VBA.InStr(at.Filename, cell1) > 0 Then
            at.SaveAsFile sh.Range("F1").Value & "\" & lr & ". " & at.Filename
       End If
    Next

Next

MsgBox "Reports have been downloaded successfully"

End Sub

I tried to change the filter string but without success.

Community
  • 1
  • 1
Joe
  • 337
  • 6
  • 21
  • 1
    Don't forget your `Set` statement. For example, `Set fo =`. – Brian M Stafford Feb 08 '19 at 13:30
  • @BrianMStafford Thanks for that! It seems that VBA now points to the line with 'for' loop. I think VBA is not happy how I define/call email items. – Joe Feb 08 '19 at 13:37
  • 1
    `Restrict` returns `Items` not a `Folder` so this is likely the issue. – Brian M Stafford Feb 08 '19 at 13:44
  • 1
    Could you try delete the line `Set fo = fo.Items.Restrict(sFilter)` and replace the line `For Each msg In fo.Items` with `For Each msg In fo.Items.Restrict(sFilter)`? – Pspl Feb 08 '19 at 15:02
  • Filter by received date https://stackoverflow.com/questions/48270942/get-email-from-outlook-to-excel-specified-by-received-date. Check that the item is a mailitem https://stackoverflow.com/questions/11729903/type-mismatch-error-when-items-in-inbox-declared-as-mailitems – niton Feb 15 '19 at 16:21

0 Answers0