I have a vba code that I have added as an outlook rule, so every time when i get daily email with a specific subject, outlook starts to run script. However,when email just received, outlook starts to run vba code immediately picking up previous email, probably because the email was just received and not moved to a specific folder yet. I tried to use Application.Wait (Now TimeValue("0:00:5")) and Outlook.Application.Wait (Now TimeValue("0:00:5")) just before grabbing the email lineSet oLookMailitem =Application.ActiveExplorer.CurrentFolder.Items("Apples Sales") and it doesn't work, vba shows an error Object doesn't support this property or method
Here is the beginning of my code:The error 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
CodePudding user response:
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.
CodePudding user response:
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.
