Quantcast
Channel: Active questions tagged excel - Stack Overflow
Viewing all articles
Browse latest Browse all 90244

How to count emails, according to criterion, from all folders and subfolders in Outlook using Excel VBA?

$
0
0

I have to count the number of mails received within certain criterion for weekly reporting. The mails are in various folders and subfolders of Outlook.

Dim objOutlook As Object, objnSpace As Object, objFolder As Outlook.MAPIFolder
Dim EmailCount As Integer

Sub HowManyDatedEmails()
    Set objOutlook = CreateObject("Outlook.Application")
    Set objnSpace = objOutlook.GetNamespace("MAPI")

    On Error Resume Next
    Set objFolder = objnSpace.GetDefaultFolder(olFolderInbox)
    If Err.Number <> 0 Then
        Err.Clear
        MsgBox "No such folder."
        Exit Sub
    End If

    Dim iCount As Integer, DateCount1 As Integer
    Dim myDate1 As Date
    Dim myDate2 As Date
    Dim DateCount2 As Integer

    EmailCount = objFolder.Items.Count
    DateCount1 = 0
    DateCount2 = 0
    myDate1 = Sheets("Sheet1").Range("A1").Value
    myDate2 = Sheets("Sheet1").Range("B1").Value

    For iCount = 1 To EmailCount
        With objFolder.Items(iCount)

            If DateSerial(Year(.ReceivedTime), Month(.ReceivedTime), Day(.ReceivedTime)) >= myDate1 And _
              DateSerial(Year(.ReceivedTime), Month(.ReceivedTime), Day(.ReceivedTime)) <= myDate2 And _
              .SenderEmailAddress Like "*kailash*" Then

                DateCount1 = DateCount1 + 1
            End If

            If DateSerial(Year(.ReceivedTime), Month(.ReceivedTime), Day(.ReceivedTime)) >= myDate1 And _
              DateSerial(Year(.ReceivedTime), Month(.ReceivedTime), Day(.ReceivedTime)) <= myDate2 And _
              .SenderEmailAddress Like "*soumendra*" Then

                DateCount2 = DateCount2 + 1
            End If

         End With
     Next iCount

    Set objFolder = Nothing
    Set objnSpace = Nothing
    Set objOutlook = Nothing
    Sheets("Sheet1").Range("B2").Value = DateCount1
    Sheets("Sheet1").Range("B3").Value = DateCount2

End Sub

I want Excel VBA code such that the sheet list shows the count figure against the criterion number.

I am able to do it for one folder but I want to achieve it for all folders and subfolders recursively in Inbox.


Viewing all articles
Browse latest Browse all 90244