'Wait for 5-10 seconds then run Outlook code
I have VBA code in an Outlook rule. I want when I get email with a specific subject, Outlook starts to run a script. However, when email is received, Outlook starts to run the code immediately picking up previous email, probably because the email was just received and not moved to a specific folder yet.
I tried
Application.Wait (Now + TimeValue("0:00:5"))
and
Outlook.Application.Wait (Now + TimeValue("0:00:5"))
just before grabbing the email with
Set oLookMailitem = Application.ActiveExplorer.CurrentFolder.Items("Apples Sales")
VBA shows an error
Object doesn't support this property or method
Here is the beginning of my code: The error occurs on Application.Wait (Now + TimeValue("0:00:5"))
.
Sub ExportOutlookTableToExcel()
Dim oLookInspector As Inspector
Dim oLookMailitem As MailItem
Dim oLookWordDoc As Word.Document
Dim oLookWordTbl As Word.Table
Dim xlApp As Excel.Application
Dim xlBook As Excel.Workbook
Dim xlWrkSheet As Excel.Worksheet
Dim Today As String
Today = Date
Application.Wait (Now + TimeValue("0:00:5"))
'Grab Email Item
Set oLookMailitem =Application.ActiveExplorer.CurrentFolder.Items("Apples Sales")
Set oLookInspector = oLookMailitem.GetInspector
Set oLookWordDoc = oLookInspector.WordEditor
Solution 1:[1]
Outlook has no Application.Wait
You can workaround this with a Do
loop, a Timer
and DoEvents
:
Public Sub Sleep(ByVal SleepSeconds As Single)
Dim Tmr As Single
Tmr = Timer
Do While Tmr + SleepSeconds > Timer
DoEvents
Loop
End Sub
And call it like Sleep 5
instead of your Application.Wait
.
Solution 2:[2]
Application.Wait
is not a panacea for your goal!
Consider using Windows API functions to set up a timer and run your actions (processing items) when it fires. See Outlook VBA - Run a code every half an hour for more information.
Also to handle incoming emails immediately you need to handle the NewMailEx event which is fired when a new message arrives in the Inbox and before client rule processing occurs. You can use the Entry ID returned in the EntryIDCollection
array to call the NameSpace.GetItemFromID method and process the item. Use this method with caution to minimize the impact on Outlook performance. However, depending on the setup on the client computer, after a new message arrives in the Inbox, processes like spam filtering and client rules that move the new message from the Inbox to another folder can occur asynchronously. You should not assume that after these events fire, you will always get a one-item increase in the number of items in the Inbox.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Pᴇʜ |
Solution 2 | Eugene Astafiev |