1

I try to search the SentMail folder for mail where To address ends with, lets say .cn and move it to a personal folder.

The code work but doesn't move all the mail, for every time I run it it's take a few more mail.

If I have 24 mails that ends with .cn it takes 13,6,3,2 so in the end it finds all the mail but not on the same run.

Anyone have any ideas?

Sub Search_SentMail()

Dim myOlApp As New Outlook.Application
Dim MyNameSpace As Outlook.NameSpace
Dim MyInbox As Outlook.MAPIFolder
Dim myitems As Outlook.Items
Dim myItem As Object

Set MyNameSpace = myOlApp.GetNamespace("MAPI")
Set MyInbox = MyNameSpace.GetDefaultFolder(olFolderInbox)
Set myOutbox = MyNameSpace.GetDefaultFolder(olFolderSentMail)
Set myitems = myOutbox.Items

Dim junk As Outlook.Folder
Set junk = MyNameSpace.GetDefaultFolder(olFolderInbox)
Set junk = junk.Folders("CN")
Count = 0
For Each myItem In myitems
If TypeOf myItem Is Outlook.MailItem Then
If Right(myItem.To, 4) = ".cn'" Then
myItem.Move junk
Count = Count + 1
End If
End If
Next myItem

Debug.Print Count
Set MyNameSpace = Nothing
Set MyInbox = Nothing
Set myOutbox = Nothing
Set myitems = Nothing
Set junk = Nothing
End Sub
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
J. Mal
  • 37
  • 1
  • 6
  • So you assume that chinese are spammers, right? ;-) Add this before the loop on `myitems`, and retry : `myitems.sort "[ReceivedTime]"` – Thomas G Sep 11 '18 at 13:08
  • Possible duplicate of [For Each loop: Some items get skipped when looping through Outlook mailbox to delete items](https://stackoverflow.com/questions/10725068/for-each-loop-some-items-get-skipped-when-looping-through-outlook-mailbox-to-de) – niton Sep 11 '18 at 20:38
  • When moving items or deleting items in a collection either loop in reverse or process item 1 until there are no more items. – niton Sep 11 '18 at 20:43

1 Answers1

0

The answer was here: For Each loop: Some items get skipped when looping through Outlook mailbox to delete items

Thanks @niton

J. Mal
  • 37
  • 1
  • 6