Move emails from one Outlook folder to another

隐身守侯 提交于 2020-01-25 07:23:06

问题


I am running this code to copy the contents from Outlook folder TODO to Outlook folder Test. Both folders exist.

I got

"Run-time error '-2147221233 (8004010f)'

for Set myItem = myInbox.Folders("TODO")

I tried

Dim myItem As Folder

Sub MoveItems() 
    Dim myNameSpace As Outlook.NameSpace 
    Dim myInbox As Outlook.Folder 
    Dim myDestFolder As Outlook.Folder 
    Dim myItems As Outlook.Items 
    Dim myItem As Object 

    Set myNameSpace = Application.GetNamespace("MAPI") 
    Set myInbox = myNameSpace.GetDefaultFolder(olFolderInbox) 
    Set myItems = myInbox.Items 
    Set myDestFolder = myInbox.Folders("test") 
    Set myItem = myInbox.Folders("TODO") 
    While TypeName(myItem) <> "Nothing" 
        myItem.Move myDestFolder 
        Set myItem = myItems.FindNext 
    Wend 
End Sub

回答1:


This will move all the Files from TODO to Test

Sub MoveItems()

 Dim myNameSpace As Outlook.NameSpace
 Dim myInbox As Outlook.Folder
 Dim myDestFolder As Outlook.Folder
 Dim myItems As Outlook.Items
 Dim myItem As Object

 Set myNameSpace = Application.GetNamespace("MAPI")
 Set myInbox = myNameSpace.GetDefaultFolder(olFolderInbox)
 Set myItems = myInbox.Items
 Set myDestFolder = myInbox.Folders("test")

 Set myItems = myInbox.Folders("TODO").Items

 'Debug.Print myItems.Count

 For i = myItems.Count To 1 Step -1 'Iterates from the end backwards
    myItems.Item(i).Move myDestFolder

 Next

End Sub

You had to loop all the items in the folder, that code was for Finding a particular mail.

Reason why we used the Loop Backwards (Courtesy: @ComputerVersteher) If you loop forward and remove an item (e.g. first one), the following items takes over position from their predecessors (e.g second-one gets first-one) andCollection.Countis decreased by one. Forward loop would try to fetch items up to startingCollection.Count, but the item with last index isn't available any longer. When moving backward, you start with the last item and if you remove it, the next item (index-1) is still available as it retains position. Btw,For Eachloops produce strange results too and should be avoided when deleting items.



来源:https://stackoverflow.com/questions/56990440/move-emails-from-one-outlook-folder-to-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!