I am trying to write simple code to download outlook attachments and save them in disk folder. I have found one that works very well. However, I need to add another If
so that only email SINCE certain date are saved. I am trying to use ReceivedTime
property and date variable (defined as rec_date
). Unfortunately, I keep getting error 438:
Here is my code:
Option Explicit
Private Sub btn_extractemails_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 rec_date As Date
Set OlApp = GetObject(, "Outlook.Application")
If Err.Number = 429 Then
Set OlApp = CreateObject("Outlook.Application")
End If
strFolder = ThisWorkbook.Path & "\Extract_test"
rec_date = #8/17/2022#
Set OlFolder = OlApp.GetNamespace("MAPI").Folders("Folder1").Folders("Folder2").Folders("Folder3") '
Set OlItems = OlFolder.Items
OlItems.Sort "[ReceivedTime]"
For Each OlMail In OlItems
If OlMail.ReceivedTime >= rec_date Then
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
End If
Next
Set OlFolder = Nothing
Set OlItems = Nothing
Set OlMail = Nothing
Set OlApp = Nothing
End Sub
According to debugger the If OlMail.ReceivedTime >= rec_date Then
is the line that gives the error. I wanted to keep my code as simple as possible but any working solution is welcome.
What might be important to note: this error appears even when I do simple some_date_variable = OlMail.ReceivedTime
(same for .SentOn
) in my code.