Jason Lee Hayes
Active member
- Local time
- Today, 14:50
- Joined
- Jul 25, 2020
- Messages
- 204
Hi,
Struggling; I'm trying to open Outlook from VBA that searches all email received from all accounts in the past 2 minutes and report true IF an email subject line contains specific words.
The following code runs; no issue but fails to identify.
Any help would be appreciated.
Struggling; I'm trying to open Outlook from VBA that searches all email received from all accounts in the past 2 minutes and report true IF an email subject line contains specific words.
The following code runs; no issue but fails to identify.
Any help would be appreciated.
Code:
Sub CheckForNewTicketInAllFolders()
Dim olApp As Outlook.Application
Dim olNamespace As Outlook.Namespace
Dim lastTwoMinutes As Date
Dim mailFound As Boolean
' Set the Outlook application
Set olApp = New Outlook.Application
Set olNamespace = olApp.GetNamespace("MAPI")
' Define the time window to check for emails (past 2 minutes)
lastTwoMinutes = Now - TimeValue("00:02:00")
mailFound = False
' Loop through all folders starting from the root
CheckFolders olNamespace.Folders, lastTwoMinutes, mailFound
' Display the appropriate message
If mailFound Then
MsgBox "Ticket has arrived!", vbInformation
Else
MsgBox "No new ticket", vbExclamation
End If
' Clean up
Set olNamespace = Nothing
Set olApp = Nothing
End Sub
Sub CheckFolders(folders As Outlook.Folders, lastTwoMinutes As Date, ByRef mailFound As Boolean)
Dim olFolder As Outlook.Folder
Dim olItems As Outlook.Items
Dim olItem As Object
For Each olFolder In folders
' Loop through items in the current folder
Set olItems = olFolder.Items
For Each olItem In olItems
' Check if the item is an email and matches the subject and time criteria
If TypeOf olItem Is Outlook.MailItem Then
If InStr(1, olItem.Subject, "Ticket received", vbTextCompare) > 0 And olItem.ReceivedTime >= lastTwoMinutes Then
mailFound = True
Exit Sub
End If
End If
Next olItem
' Recursively check subfolders
If olFolder.Folders.Count > 0 Then
CheckFolders olFolder.Folders, lastTwoMinutes, mailFound
End If
Next olFolder
End Sub