Danny Papadopulos
Danny Papadopulos

Reputation: 465

Pause/Stop downloading new emails while running VBA macro in Outlook [pause/stop sync]

I'm new to VBA Programming in Outlook.

I'm writing a macro which scans inbox and moves emails to specific folders by checking criteria such as subject, sender, body etc.

Now the problem is that when I loop through the mailbox and a new email comes in, the loop breaks.

First possible solution to this that came to my head was disabling email synchronization for the time when macro is running. I researched this further and found the Sync Object in Outlook VBA with the method Sync.Start and Sync.Stop.

docs Microsoft - SyncObject.Start method

So I declared all variables like in the link and tried the code. Everything seems to be executed without errors, I loop through all the sync objects and stop them however I noticed that emails come to my inbox anyway.

Public Sub Sync() 
 Dim nsp As Outlook.NameSpace 
 Dim sycs As Outlook.SyncObjects 
 Dim syc As Outlook.SyncObject 
 Dim i As Integer 

Set nsp = Application.GetNamespace("MAPI") 
Set sycs = nsp.SyncObjects 

For i = 1 To sycs.Count 
    Set syc = sycs.Item(i) 
    syc.Stop  
Next 
End Sub

Any ideas how to make this work or other ideas how to overcome this problem are greatly appreciated. Thanks

[EDIT 1, 07.05.2020, 20:29] Thanks for your comments guys, I just got another idea in my head. I could create a temporary folder, move all emails that satisfy my criteria from inbox into this temporary folder, sort those emails to other folders from that temp folder. This should work because no new emails will be coming to the temp folder unlike inbox!

Upvotes: 0

Views: 356

Answers (2)

Eugene Astafiev
Eugene Astafiev

Reputation: 49455

Instead of iterating over all items in the folder and don't break the loop when a new item arrives, I'd recommend using the Find/FindNext or Restrict methods where you can find only items that correspond to your conditions. Read more about these methods in the following articles:

Also, you can process items by small chunks by finding all items for a week or month and etc.

Upvotes: 0

Dmitry Streblechenko
Dmitry Streblechenko

Reputation: 66316

Firstly, please show your code that processes the items.

Secondly, you can sort your collection (Items.Sort) on ReceivedTime and process the Items collection backwards (Items.Count to 1 step -1)

Upvotes: 1

Related Questions