Home > Net >  Extracting Emails from Outlook
Extracting Emails from Outlook

Time:02-01

Thank you in advance!

I want to extract emails from Outlook. I'm a complete begginer

I tried this code which was already there but was not working properly, showing an Error code (438).

Option Explicit

Sub ExtraerCorreos()

Dim OutlookApp As Object
Dim ONameSpace As Object
Dim MyFolder As Object
Dim OItem As Object
Dim Fila As Integer

Dim Fecha As Date

Set OutlookApp = New Outlook.Application
Set ONameSpace = OutlookApp.GetNamespace("MAPI")
Set MyFolder = ONameSpace.GetDefaultFolder(olFolderInbox)

Fila = 2

Fecha = "24/01/2023"

For Each OItem In MyFolder.Items

If Int(OItem.ReceivedTime) >= Fecha Then

        Sheets("Hoja1").Cells(Fila, 1).Value = OItem.SenderEmailAddress
        Sheets("Hoja1").Cells(Fila, 2).Value = OItem.Subject
        Sheets("Hoja1").Cells(Fila, 3).Value = OItem.ReceivedTime
        Sheets("Hoja1").Cells(Fila, 4).Value = OItem.Body
       
End If
   
        Fila = Fila   1
   
Next OItem

Set OutlookApp = Nothing
Set ONameSpace = Nothing
Set MyFolder = Nothing


End Sub

Thank you!

CodePudding user response:

In the code you are iterating over all items in the folder:

For Each OItem In MyFolder.Items

If Int(OItem.ReceivedTime) >= Fecha Then

        Sheets("Hoja1").Cells(Fila, 1).Value = OItem.SenderEmailAddress
        Sheets("Hoja1").Cells(Fila, 2).Value = OItem.Subject
        Sheets("Hoja1").Cells(Fila, 3).Value = OItem.ReceivedTime
        Sheets("Hoja1").Cells(Fila, 4).Value = OItem.Body
       
End If

Keep in mind that Outlook folders may contain different kind of items - mails, appointments, notes and etc. So, there is a high risk to use a property on an object which doesn't provide such property or method.

The error 438 occurs when you try to use a property or method that does not support by that object. as you know all objects have some properties and methods that you can use but there could be a situation when using a property or method that does not apply to a particular object.

So, I'd suggest checking the item type or message class (see the MessageClass property) before processing an item in the loop, so you could be sure such properties do exist, for example:

For Each OItem In MyFolder.Items

    If TypeName(OItem) = "MailItem" Then
        Set oMail = oItem

        'do stuff with omail
    End If

Next

Also, instead of iterating over all items and checking the ReceivedTime property in the loop you can use the Find/FindNext or Restrict methods of the Items class. They allow getting items that correspond to the search criteria, so you will iterate only through the items you need. Read more about these methods in the articles I wrote for the technical blog:

CodePudding user response:

You declared Fecha as a date but assigned Fecha= "24/01/2023" which is a string. Try Fecha = #24/01/2023# or Fecha = DateValue("24/01/2023")

  • Related